"""
GENAURA, génération du PDF.

Le PDF contient :
  - L'en-tête La Poste.
  - Les informations de l'appel.
  - Le résumé d'appel interne (traçabilité).
  - Le mail envoyé au client (français + langue cible si bilingue).
  - Une mention de validation.

Stratégie de polices :
  - Si une police Unicode est trouvée (Tahoma sur Windows par défaut, ou DejaVu Sans
    si présente dans data/fonts/), elle est utilisée pour tout le PDF.
  - Sinon, fallback sur Helvetica avec nettoyage Latin-1.

Stratégie pour l'arabe :
  - Si arabic-reshaper et python-bidi sont installés, le texte arabe est correctement
    reshapé (lettres connectées) et orienté de droite à gauche.
  - Sinon, le texte arabe est rendu tel quel.
"""

from fpdf import FPDF
from datetime import datetime
import os

# Détection des libs optionnelles pour l'arabe
try:
    import arabic_reshaper
    from bidi.algorithm import get_display
    ARABE_RENDU_DISPONIBLE = True
except ImportError:
    ARABE_RENDU_DISPONIBLE = False


def trouver_police_unicode():
    """Cherche une police TTF Unicode. Retourne le chemin ou None."""
    chemins_candidats = [
        "data/fonts/DejaVuSans.ttf",
        "data/fonts/NotoSans-Regular.ttf",
        "C:/Windows/Fonts/tahoma.ttf",
        "C:/Windows/Fonts/arial.ttf",
        "/System/Library/Fonts/Supplemental/Tahoma.ttf",
        "/Library/Fonts/Arial Unicode.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
        "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
    ]
    for chemin in chemins_candidats:
        if os.path.exists(chemin):
            return chemin
    return None


REMPLACEMENTS_UNICODE = {
    "\u2014": " - ", "\u2013": "-",
    "\u2212": "-", "\u2010": "-", "\u2011": "-",
    "\u201C": '"', "\u201D": '"',
    "\u2018": "'", "\u2019": "'",
    "\u00AB": '"', "\u00BB": '"',
    "\u201E": '"', "\u201A": "'",
    "\u2039": "<", "\u203A": ">",
    "\u2026": "...",
    "\u2022": "-", "\u00B7": ".",
    "\u25E6": "-", "\u25A0": "-", "\u25A1": "-",
    "\u25CF": "-", "\u25CB": "-",
    "\u2192": "->", "\u2190": "<-",
    "\u21D2": "=>", "\u21D0": "<=",
    "\u00A0": " ", "\u202F": " ", "\u2009": " ", "\u200B": "",
    "\u2122": "(TM)", "\u00AE": "(R)", "\u00A9": "(C)",
}


def nettoyer_latin1(texte: str) -> str:
    """Nettoie pour Helvetica (fallback)."""
    if not texte:
        return ""
    for c, r in REMPLACEMENTS_UNICODE.items():
        texte = texte.replace(c, r)
    texte = texte.encode("latin-1", errors="replace").decode("latin-1")
    return texte


def reshaper_arabe(texte: str) -> str:
    """Reshape un texte arabe pour rendu PDF correct."""
    if not ARABE_RENDU_DISPONIBLE or not texte:
        return texte
    try:
        configuration = {
            'delete_harakat': False,
            'support_ligatures': True,
        }
        reshaper = arabic_reshaper.ArabicReshaper(configuration)
        texte_reshape = reshaper.reshape(texte)
        texte_bidi = get_display(texte_reshape)
        return texte_bidi
    except Exception:
        return texte


def contient_arabe(texte: str) -> bool:
    """Détecte la présence de caractères arabes."""
    if not texte:
        return False
    for c in texte:
        if '\u0600' <= c <= '\u06FF':
            return True
    return False


def generer_pdf_resume(
    nom_client: str,
    ref_client: str,
    nom_conseiller: str,
    resume_valide: str,
    id_appel: str,
    email_envoye: str = "",
    langue_mail: str = "FR",
    output_path: str = None
) -> str:
    """Génère un PDF complet incluant résumé et mail envoyé."""
    if output_path is None:
        output_path = f"./archives/{id_appel}_resume.pdf"

    chemin_police = trouver_police_unicode()
    police_unicode = chemin_police is not None

    pdf = FPDF()
    pdf.add_page()

    if police_unicode:
        pdf.add_font("Uni", "", chemin_police, uni=True)
        nom_police = "Uni"

        def ecrire(texte: str) -> str:
            if contient_arabe(texte):
                return reshaper_arabe(texte)
            return texte
    else:
        nom_police = "Helvetica"

        def ecrire(texte: str) -> str:
            return nettoyer_latin1(texte)

    # En-tête
    pdf.set_font(nom_police, "", 16)
    pdf.cell(0, 10, ecrire("La Poste - Compte rendu d'appel"), ln=True, align="C")
    pdf.ln(5)
    pdf.set_draw_color(255, 204, 0)
    pdf.set_line_width(1)
    pdf.line(10, pdf.get_y(), 200, pdf.get_y())
    pdf.ln(8)

    # Informations
    pdf.set_font(nom_police, "", 11)
    pdf.cell(0, 7, ecrire(f"Référence appel : {id_appel}"), ln=True)
    pdf.cell(0, 7, ecrire(f"Client : {nom_client} (réf. {ref_client})"), ln=True)
    pdf.cell(0, 7, ecrire(f"Conseiller : {nom_conseiller}"), ln=True)
    pdf.cell(
        0, 7,
        ecrire(f"Date : {datetime.now().strftime('%d/%m/%Y à %H:%M')}"),
        ln=True
    )
    pdf.cell(0, 7, ecrire(f"Langue du mail client : {langue_mail}"), ln=True)
    pdf.ln(8)

    # Section 1, résumé interne
    pdf.set_font(nom_police, "", 13)
    pdf.cell(0, 8, ecrire("1. Résumé interne (traçabilité)"), ln=True)
    pdf.ln(2)
    pdf.set_font(nom_police, "", 10)
    resume_clean = (
        resume_valide
        .replace("### ", "").replace("## ", "").replace("# ", "")
        .replace("**", "").replace("*", "")
    )
    pdf.multi_cell(0, 6, ecrire(resume_clean))
    pdf.ln(8)

    # Section 2, mail envoyé au client
    if email_envoye:
        pdf.set_font(nom_police, "", 13)
        pdf.cell(0, 8, ecrire("2. Mail envoyé au client"), ln=True)
        pdf.ln(2)
        pdf.set_font(nom_police, "", 10)

        if "---" in email_envoye:
            parties = email_envoye.split("---")
            for i, partie in enumerate(parties):
                partie = partie.strip()
                if not partie:
                    continue
                partie = (
                    partie
                    .replace("=== VERSION FRANÇAISE ===", "Version française :")
                    .replace("=== VERSION ENGLISH ===", "English version:")
                    .replace("=== VERSION ESPAÑOL ===", "Versión española:")
                    .replace("=== VERSION العربية ===", "Version arabe :")
                )
                if contient_arabe(partie) and police_unicode:
                    pdf.multi_cell(0, 6, ecrire(partie), align="R")
                else:
                    pdf.multi_cell(0, 6, ecrire(partie))
                if i < len(parties) - 1:
                    pdf.ln(3)
                    pdf.set_draw_color(200, 200, 200)
                    pdf.line(10, pdf.get_y(), 200, pdf.get_y())
                    pdf.ln(3)
        else:
            pdf.multi_cell(0, 6, ecrire(email_envoye))

        pdf.ln(8)

    # Mention de validation
    pdf.set_font(nom_police, "", 9)
    pdf.set_text_color(100, 100, 100)
    pdf.cell(
        0, 6,
        ecrire(
            f"Document validé par {nom_conseiller} "
            f"le {datetime.now().strftime('%d/%m/%Y à %H:%M')}."
        ),
        ln=True
    )
    pdf.cell(
        0, 6,
        ecrire("Document généré par GENAURA, copilote post-appel La Poste."),
        ln=True
    )

    # Avertissement si arabe mais pas de police Unicode
    if not police_unicode and contient_arabe(email_envoye):
        pdf.ln(3)
        pdf.set_text_color(180, 0, 0)
        pdf.cell(
            0, 5,
            "Note : police Unicode non trouvee, partie arabe non rendue dans le PDF.",
            ln=True
        )

    pdf.output(output_path)
    return output_path