#!/usr/bin/env python3
"""2e passe : uniquement les textes encore en anglais → FR via Google."""
from __future__ import annotations

import json
import re
import time
from pathlib import Path

from deep_translator import GoogleTranslator

DIR = Path(__file__).resolve().parent
JSON_PATH = DIR / "classified_all.json"
CACHE_PATH = DIR.parent / "translate_cache_fr.json"

FIELDS = [
    "summary",
    "pain_point",
    "objections",
    "next_step",
    "urgency",
    "budget",
    "scam_type",
    "case_status",
    "payment",
]


def is_english(text: str) -> bool:
    if not text or len(text.strip()) < 3:
        return False
    t = text.strip()
    if re.fullmatch(r"[\d\s.,€$+\-_/]+", t):
        return False
    if re.search(r"[\u0600-\u06FF]", t):
        return True
    low = t.lower()
    eng = len(
        re.findall(
            r"\b(the|and|with|for|from|this|that|customer|interested|follow|called|expressed|"
            r"recovery|account|scam|funds|looking|wants|needs|about|their|have|has|was|were|"
            r"will|would|process|assistance|investment|platform|email|phone|call|next|step|"
            r"she|he|they|his|her|been|being)\b",
            low,
        )
    )
    fr = len(
        re.findall(
            r"\b(le|la|les|des|une|un|est|sont|pour|avec|dans|sur|pas|qui|que|"
            r"appel|client|arnaque|compte|fonds|intéressé|suite|elle|il|ils|son|sa)\b",
            low,
        )
    )
    if eng >= 2 and eng > fr:
        return True
    if eng >= 1 and fr == 0 and not re.search(r"[àâäéèêëïîôùûüç]", low):
        return True
    return False


def dash(v: str) -> str:
    return v if v else "—"


def build_notes_fr(c: dict) -> str:
    status_map = {"hot": "chaud", "warm": "tiède", "cold": "froid"}
    st = status_map.get((c.get("status_temp") or "").lower(), c.get("status_temp") or "—")
    phone = c.get("phone") or ""
    if phone and not str(phone).startswith("+"):
        phone = "+" + "".join(ch for ch in phone if ch.isdigit())
    typ = c.get("type") or c.get("industry") or "—"
    return "\n".join(
        [
            "═══ FICHE CONTACT (import batch) ═══",
            f"Source : {c.get('source_file') or '—'}",
            f"Priorité CRM : {c.get('priority') or 'moyenne'}",
            f"Type : {typ}",
            f"Statut temporaire : {st}",
            "",
            "── Identité ──",
            f"Nom : {dash(c.get('name') or '')}",
            f"Téléphone : {dash(phone)}",
            f"E-mail : {dash(c.get('email') or '')}",
            f"Pays : {dash(c.get('country') or 'France')}",
            f"Langue : {dash(c.get('language') or '')}",
            "",
            "── Commercial ──",
            f"Industrie : {dash(c.get('industry') or typ)}",
            f"Courtier : {dash(c.get('broker') or '')}",
            f"Dépôt : {dash(c.get('deposit') or '')}",
            f"Étape FTD : {dash(c.get('ftd_stage') or '')}",
            f"Urgence : {dash(c.get('urgency') or '')}",
            f"Budget : {dash(c.get('budget') or '')}",
            "",
            "── Recovery ──",
            f"Montant perdu : {dash(c.get('amount_lost') or '')}",
            f"Type d'arnaque : {dash(c.get('scam_type') or '')}",
            f"Statut du dossier : {dash(c.get('case_status') or '')}",
            f"Banque : {dash(c.get('bank') or '')}",
            f"Paiement : {dash(c.get('payment') or '')}",
            "",
            "── Synthèse ──",
            f"Point de douleur : {dash(c.get('pain_point') or '')}",
            f"Objections : {dash(c.get('objections') or '')}",
            f"Résumé : {dash(c.get('summary') or '')}",
            f"Prochaine étape : {dash(c.get('next_step') or '')}",
            "",
            f"Date du lead : {dash(c.get('lead_date') or '')}",
            f"Code de sécurité : {dash(c.get('security_code') or '')}",
        ]
    )


def google_fr(text: str, retries: int = 4) -> str:
    src = "ar" if re.search(r"[\u0600-\u06FF]", text) else "auto"
    for attempt in range(retries):
        try:
            time.sleep(1.0 + attempt * 0.5)
            # découper
            if len(text) <= 4500:
                return GoogleTranslator(source=src, target="fr").translate(text)
            parts = []
            rem = text
            while len(rem) > 4000:
                cut = rem.rfind(". ", 0, 4000)
                if cut < 100:
                    cut = 4000
                parts.append(rem[: cut + 1].strip())
                rem = rem[cut + 1 :].strip()
            if rem:
                parts.append(rem)
            out = []
            for p in parts:
                time.sleep(1.0)
                out.append(GoogleTranslator(source=src, target="fr").translate(p))
            return " ".join(out)
        except Exception as e:
            print(f"  retry {attempt+1}: {e}", flush=True)
            time.sleep(2 + attempt)
    return text


def main() -> None:
    cache = {}
    if CACHE_PATH.exists():
        try:
            cache = json.loads(CACHE_PATH.read_text(encoding="utf-8"))
        except Exception:
            cache = {}

    contacts = json.loads(JSON_PATH.read_text(encoding="utf-8"))
    # collect unique EN strings
    todo: list[str] = []
    for c in contacts:
        for f in FIELDS:
            v = (c.get(f) or "").strip()
            if v and is_english(v) and v not in todo:
                todo.append(v)

    print(f"Unique EN strings remaining: {len(todo)}", flush=True)
    for i, text in enumerate(todo, 1):
        print(f"[{i}/{len(todo)}] {text[:60].encode('ascii','replace').decode()}...", flush=True)
        if text in cache and not is_english(cache[text]):
            continue
        fr = google_fr(text)
        cache[text] = fr
        if i % 10 == 0:
            CACHE_PATH.write_text(json.dumps(cache, ensure_ascii=False), encoding="utf-8")

    CACHE_PATH.write_text(json.dumps(cache, ensure_ascii=False), encoding="utf-8")

    # apply
    for c in contacts:
        for f in FIELDS:
            v = (c.get(f) or "").strip()
            if v and v in cache:
                c[f] = cache[v]
            elif v and is_english(v):
                c[f] = google_fr(v)
                cache[v] = c[f]
        c["notes"] = build_notes_fr(c)

    JSON_PATH.write_text(json.dumps(contacts, ensure_ascii=False, indent=2), encoding="utf-8")
    import regen_clients_sql as regen

    regen.main()

    sql = (DIR / "import_ready.sql").read_text(encoding="utf-8")
    for p in ["The customer", "The call", "interested in", "follow-up", "expressed"]:
        print(f"SQL leftover '{p}': {sql.count(p)}", flush=True)
    left = sum(
        1
        for c in contacts
        if is_english(c.get("summary") or "")
        or is_english(c.get("pain_point") or "")
        or is_english(c.get("objections") or "")
    )
    print(f"contacts still EN: {left}", flush=True)
    print("DONE", flush=True)


if __name__ == "__main__":
    main()
