"""
pytest-translate — Terminal pytest dans ta langue natale
=========================================================
Par Julien Mer / JMer Consulting

Traduit automatiquement la sortie terminal de pytest dans la langue
de ton OS — ou dans la langue de ton choix via --translate-lang.

Usage :
  pytest tests/                             # auto-détection locale OS
  pytest tests/ --translate-lang=zh_CN      # force le chinois
  pytest tests/ --translate-lang=yi         # yiddish
  pytest tests/ --translate-lang=sa         # sanskrit
  pytest tests/ --translate-lang=off        # désactive la traduction

Installation :
  pip install pytest-translate

Note : sans réseau ou sans deep-translator, le plugin revient
       silencieusement au texte source. Il ne casse jamais une session.
"""

import locale
import os

# ============================================================
# ETAT GLOBAL — résolu une seule fois dans pytest_configure
# ============================================================

_ACTIVE_LANG = None
_CACHE = {}


def _resolve_lang(config):
    """Résout la langue active une seule fois au démarrage."""
    global _ACTIVE_LANG
    try:
        val = config.getoption("--translate-lang", default=None, skip=True)
    except Exception:
        val = None
    if val is None:
        val = os.getenv("PYTEST_LANG", "auto")
    if val == "off" or val is None:
        _ACTIVE_LANG = None
        return
    if val == "auto":
        try:
            lang = locale.getlocale()[0]
        except Exception:
            lang = None
        _ACTIVE_LANG = lang if lang and not lang.startswith("en") else None
        return
    _ACTIVE_LANG = val if not val.startswith("en") else None


def _normalize_code(lang):
    """Normalise le code langue pour deep_translator."""
    if not lang:
        return None
    low = lang.lower()
    if low.startswith("zh"):
        return "zh-CN" if "tw" not in low else "zh-TW"
    return lang.replace("_", "-").split("-")[0]


def _t(text):
    """Traduit un texte dans la langue active — silencieux si echec."""
    if not _ACTIVE_LANG:
        return text
    key = f"{_ACTIVE_LANG}:{text}"
    if key in _CACHE:
        return _CACHE[key]
    try:
        from deep_translator import GoogleTranslator
        code = _normalize_code(_ACTIVE_LANG)
        result = GoogleTranslator(source="auto", target=code).translate(text)
        _CACHE[key] = result
        return result
    except Exception:
        _CACHE[key] = text
        return text


# ============================================================
# HOOKS PYTEST
# ============================================================

def pytest_addoption(parser):
    """Ajoute l'option --translate-lang a pytest."""
    parser.addoption(
        "--translate-lang",
        action="store",
        default=None,
        metavar="LANG",
        help=(
            "Langue du terminal pytest. "
            "Ex: zh_CN, fr_FR, de_DE, ja, yi, sa, ar, hi... "
            "Valeurs speciales: auto (locale OS, defaut), off (desactive). "
            "134 langues supportees via Google Translate."
        ),
    )


def pytest_configure(config):
    """Resout la langue active une seule fois au demarrage."""
    _resolve_lang(config)
    _patch_summary_stats()
    # Supprimer short_test_summary natif si traduction active
    if _ACTIVE_LANG:
        try:
            config.option.reportchars = ""
        except Exception:
            pass


def pytest_report_teststatus(report, config):
    """Traduit les statuts PASSED / FAILED / ERROR / SKIPPED."""
    if not _ACTIVE_LANG or report.when != "call":
        return
    if report.passed:
        return report.outcome, ".", _t("PASSED")
    elif report.failed:
        return report.outcome, "F", _t("FAILED")
    elif report.skipped:
        return report.outcome, "s", _t("SKIPPED")


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """Traduit et reecrit le resume final."""
    if not _ACTIVE_LANG:
        return

    tr = terminalreporter
    passed  = len(tr.stats.get("passed",  []))
    failed  = len(tr.stats.get("failed",  []))
    error   = len(tr.stats.get("error",   []))
    skipped = len(tr.stats.get("skipped", []))

    # Duree compatible pytest 7.x et 9.x
    try:
        elapsed = tr._session_start.elapsed()
        duration_str = f"{elapsed.seconds:.2f}s"
    except Exception:
        try:
            import time
            duration_str = f"{time.time() - tr._session_start:.2f}s"
        except Exception:
            duration_str = ""

    parts = []
    if failed:  parts.append(f"{failed} {_t('failed')}")
    if error:   parts.append(f"{error} {_t('error')}")
    if passed:  parts.append(f"{passed} {_t('passed')}")
    if skipped: parts.append(f"{skipped} {_t('skipped')}")
    if not parts:
        parts.append(_t("no tests ran"))

    summary = ", ".join(parts)
    line = f"{summary} {_t('in')} {duration_str}" if duration_str else summary

    # Supprimer summary_stats natif de pytest avec restauration garantie
    original = tr.__class__.summary_stats
    tr.__class__.summary_stats = lambda self: None
    try:
        tr.write_sep("=", line, bold=True)
    finally:
        tr.__class__.summary_stats = original


def _patch_summary_stats():
    """Patch summary_stats avec restauration garantie via un flag."""
    try:
        from _pytest.terminal import TerminalReporter
        original = TerminalReporter.summary_stats

        def patched_summary_stats(self):
            if _ACTIVE_LANG:
                return  # on laisse pytest_terminal_summary gérer
            original(self)

        TerminalReporter.summary_stats = patched_summary_stats
    except Exception:
        pass