import locale
import os


MESSAGES = {
    "en": {
        "interrupted": "Interrupted.",
        "prompt_interrupted": "Interrupted. (r)estore from snapshot, (c)ontinue, (a)bort? [a]: ",
        "prompt_approve": "Proceed? [y/N]: ",
        "abort": "Aborted.",
        "manager_missing": "No conda/mamba/micromamba found in PATH; some actions are unavailable.",
        "rollback_plan": "rollback plan: {from_rev} -> {to_rev}",
        "rollback_no_revisions": "no conda revisions found for this environment",
        "rollback_invalid_target": "invalid rollback target: {to}",
        "rollback_done": "rollback done: {to_rev}",
        "rebuild_plan": "rebuild plan: {src} -> {dst}",
        "rebuild_done": "rebuild done: {dst}",
        "rebuild_target_exists": "rebuild target already exists: {dst}",
        "rebuild_need_yes": "rebuild requires confirmation (use -y/--yes to skip prompt)",
        "plan_only": "plan-only (no changes applied)",
        "clobber_header": "clobber diagnosis:",
        "clobber_no_log": "no logfile provided",
        "clobber_no_paths": "no conflict paths found in log",
        "clobber_log_read_failed": "failed to read logfile: {path}",
        "inconsistent_header": "inconsistent diagnosis:",
        "inconsistent_found": "environment is inconsistent",
        "inconsistent_not_found": "no inconsistency warning detected",
        "inconsistent_fix_plan": "fix-inconsistent plan (level={level}): {env}",
        "inconsistent_fix_done": "fix-inconsistent done (level={level})",
        "cache_header": "cache check:",
        "cache_pkgs_dirs": "pkgs_dirs: {value}",
        "cache_fix_plan": "cache-fix plan (level={level})",
        "cache_fix_done": "cache-fix done (level={level})",
        "ssl_header": "ssl diagnosis:",
        "ssl_ok": "ssl import ok: {value}",
        "ssl_fail": "ssl import failed: {value}",
        "ssl_hint": "hint: try `mamba install -n base openssl ca-certificates certifi` (or `conda install ...`), and ensure proper conda activation in your shell",
        "help_desc": "Scan and repair conda/mamba/micromamba environments with mixed conda/pip installs.",
        "help_help": "Show this help message and exit.",
        "help_env_multi": "Environment name(s) or path(s). Repeatable. Default: all discovered envs.",
        "help_fix": "Attempt repairs (safe-ish).",
        "help_adopt_pip": "Try to replace pip-installed packages with conda ones.",
        "help_keep_pip": "Keep the original pip-installed packages even if adopt-pip succeeds (default: uninstall pip version).",
        "help_prefer": "Preferred installer when fixing duplicates.",
        "help_pip_fallback": "Allow pip reinstall if conda reinstall fails.",
        "help_no_pip_fallback": "Disable pip fallback.",
        "help_channel": "Add conda channel(s). Repeatable.",
        "help_no_channels_from_condarc": "Ignore channels from .condarc/conda config.",
        "help_no_default_channels": "Do not auto-add defaults/anaconda.",
        "help_ignore_pinned": "Ignore conda pinned specs during installs.",
        "help_force_reinstall": "Force reinstall packages via conda.",
        "help_snapshot": "Write env export YAML to this path (conda envs only).",
        "help_json": "Output machine-readable JSON.",
        "help_debug": "Verbose debug logging + show JSON tool output.",
        "help_cmd_rollback": "Rollback a conda env to an earlier revision.",
        "help_cmd_rebuild": "Rebuild an env into a new env (export/import).",
        "help_cmd_diagnose_clobber": "Parse a conda/mamba ClobberError log and find file owners.",
        "help_cmd_diagnose_inconsistent": 'Check whether an env is "inconsistent" (conda warning).',
        "help_cmd_fix_inconsistent": 'Attempt to repair an "inconsistent" env.',
        "help_cmd_cache_check": "Show conda package cache locations.",
        "help_cmd_cache_fix": "Clean conda package caches.",
        "help_cmd_diagnose_ssl": "Diagnose SSL/OpenSSL issues (advisor).",
        "help_env_single": "Environment name or path.",
        "help_to": "Target: prev|latest|<N> (default: prev).",
        "help_dry_run": "Only simulate the action.",
        "help_yes": "Do not ask for confirmation.",
        "help_plan": "Only show plan (no changes).",
        "help_to_rebuild": "Target env name or path.",
        "help_verify": "Scan the new env after creation.",
        "help_logfile": "Path to conda/mamba output log text.",
        "help_level_inconsistent": "Fix level.",
        "help_level_cache": "Clean level.",
        "help_base": "Diagnose base/root prefix.",
    "progress_envs": "envs",
        "step_scan": "scan",
        "step_snapshot": "snapshot",
        "step_fix": "fix",
        "step_adopt_pip": "adopt-pip",
        "adopt_search": "mamba search batch",
        "adopt_resolve": "adopt-pip resolve",
        "env_header": "== {name} ==",
        "path": "path: {value}",
        "python": "python: {value}",
        "channels": "channels: {value}",
        "snapshot": "snapshot: {path} {status}",
        "snapshot_ok": "ok",
        "snapshot_failed": "failed",
        "issues_none": "issues: none",
        "issues": "issues:",
        "pinned": "pinned:",
        "fixes_none": "fixes: none",
        "fixes": "fixes:",
        "issue_duplicate_dist_info": " - duplicate-dist-info: {package} {versions}",
        "issue_duplicate_pyd": " - duplicate-pyd: {base} {files}",
        "issue_invalid_artifact": " - invalid-artifact: {name}",
        "issue_generic": " - {type}",
        "fix_line": " - {label} {method} {status}",
        "fix_ok": "ok",
        "fix_failed": "failed",
        "fix_report": "fix report:",
        "fix_report_none": "no fixes applied",
        "col_action": "action",
        "col_item": "item",
        "col_result": "result",
        "col_reason": "reason",
        "reason_stale_artifact": "stale/invalid artifact in site-packages",
        "reason_duplicate_dist_info": "duplicate .dist-info entries detected",
        "reason_conda_meta_reinstall": "broken conda-meta record(s) (missing depends / invalid json)",
        "reason_case_conflict_pip_uninstall": "pip+conda installed same version with different name casing",
        "reason_case_conflict_conda_relink": "relink conda package after removing pip duplicate",
        "reason_reinstall_duplicates": "reinstall to resolve duplicates",
        "reason_adopt_conda_install": "install mapped conda packages for pip-installed candidates",
        "reason_adopt_skip_keep": "keep {pip} (pip {pip_version}) because conda {conda} version is {conda_version}",
        "reason_adopt_pip_uninstall": "remove pip duplicates after conda install (only when versions match)",
        "reason_adopt_pip_force_uninstall": "remove pip package because a conda replacement is present",
        "reason_adopt_conda_relink": "relink conda packages after pip uninstall",
    },
    "de": {
        "interrupted": "Abgebrochen.",
        "prompt_interrupted": "Abgebrochen. (r)estore aus Snapshot, (c)ontinue, (a)bort? [a]: ",
        "prompt_approve": "Fortfahren? [j/N]: ",
        "abort": "Abgebrochen.",
        "manager_missing": "Kein conda/mamba/micromamba im PATH gefunden; manche Aktionen sind nicht verfuegbar.",
        "rollback_plan": "Rollback-Plan: {from_rev} -> {to_rev}",
        "rollback_no_revisions": "keine conda Revisions fuer dieses Environment gefunden",
        "rollback_invalid_target": "ungueltiges Rollback-Ziel: {to}",
        "rollback_done": "Rollback fertig: {to_rev}",
        "rebuild_plan": "Rebuild-Plan: {src} -> {dst}",
        "rebuild_done": "Rebuild fertig: {dst}",
        "rebuild_target_exists": "Rebuild-Ziel existiert bereits: {dst}",
        "rebuild_need_yes": "Rebuild braucht Bestaetigung (mit -y/--yes ohne Rueckfrage)",
        "plan_only": "nur Plan (keine Aenderungen)",
        "clobber_header": "Clobber-Diagnose:",
        "clobber_no_log": "keine Logdatei angegeben",
        "clobber_no_paths": "keine Konfliktpfade im Log gefunden",
        "clobber_log_read_failed": "Logdatei konnte nicht gelesen werden: {path}",
        "inconsistent_header": "Inconsistent-Diagnose:",
        "inconsistent_found": "Environment ist inconsistent",
        "inconsistent_not_found": "keine Inconsistency-Warnung erkannt",
        "inconsistent_fix_plan": "Fix-Inconsistent Plan (level={level}): {env}",
        "inconsistent_fix_done": "Fix-Inconsistent fertig (level={level})",
        "cache_header": "Cache-Check:",
        "cache_pkgs_dirs": "pkgs_dirs: {value}",
        "cache_fix_plan": "Cache-Fix Plan (level={level})",
        "cache_fix_done": "Cache-Fix fertig (level={level})",
        "ssl_header": "SSL-Diagnose:",
        "ssl_ok": "ssl import ok: {value}",
        "ssl_fail": "ssl import fehlgeschlagen: {value}",
        "ssl_hint": "Hinweis: ggf. `mamba install -n base openssl ca-certificates certifi` (oder `conda install ...`) und korrekte conda Aktivierung im Terminal pruefen",
        "help_desc": "Scan und Repair fuer conda/mamba/micromamba Environments mit gemischten conda/pip Installationen.",
        "help_help": "Hilfe anzeigen und beenden.",
        "help_env_multi": "Environment Name(n) oder Pfad(e). Wiederholbar. Default: alle gefundenen Envs.",
        "help_fix": "Reparaturen ausfuehren (safe-ish).",
        "help_adopt_pip": "Versuche pip-installierte Pakete durch conda Pakete zu ersetzen.",
        "help_keep_pip": "pip-Version behalten, auch wenn adopt-pip erfolgreich ist (Default: pip-Version entfernen).",
        "help_prefer": "Bevorzugter Installer beim Fixen von Duplikaten.",
        "help_pip_fallback": "pip Reinstall erlauben, wenn conda/mamba fehlschlaegt.",
        "help_no_pip_fallback": "pip Fallback deaktivieren.",
        "help_channel": "Conda Channel(s) hinzufuegen. Wiederholbar.",
        "help_no_channels_from_condarc": "Channels aus .condarc/conda config ignorieren.",
        "help_no_default_channels": "defaults/anaconda nicht automatisch hinzufuegen.",
        "help_ignore_pinned": "Conda Pins (pinned specs) beim Install ignorieren.",
        "help_force_reinstall": "Pakete via conda/mamba erneut installieren (force-reinstall).",
        "help_snapshot": "Env-Export YAML nach diesem Pfad schreiben (nur conda Envs).",
        "help_json": "Maschinenlesbares JSON ausgeben.",
        "help_debug": "Debug-Ausgabe + JSON Tool-Output anzeigen.",
        "help_cmd_rollback": "Rollback eines conda Envs auf eine fruehere Revision.",
        "help_cmd_rebuild": "Rebuild: Env exportieren und als neues Env neu erstellen.",
        "help_cmd_diagnose_clobber": "ClobberError Log parsen und Datei-Owner bestimmen.",
        "help_cmd_diagnose_inconsistent": 'Pruefen, ob ein Env "inconsistent" ist (conda Warnung).',
        "help_cmd_fix_inconsistent": 'Versuch, ein "inconsistent" Env zu reparieren.',
        "help_cmd_cache_check": "Conda Package Cache Locations anzeigen.",
        "help_cmd_cache_fix": "Conda Package Caches bereinigen.",
        "help_cmd_diagnose_ssl": "SSL/OpenSSL Probleme diagnostizieren (Advisor).",
        "help_env_single": "Environment Name oder Pfad.",
        "help_to": "Ziel: prev|latest|<N> (Default: prev).",
        "help_dry_run": "Aktion nur simulieren.",
        "help_yes": "Keine Rueckfrage (auto bestaetigen).",
        "help_plan": "Nur Plan anzeigen (keine Aenderungen).",
        "help_to_rebuild": "Ziel-Environment Name oder Pfad.",
        "help_verify": "Neues Env nach Erstellung scannen.",
        "help_logfile": "Pfad zur conda/mamba Output-Logdatei.",
        "help_level_inconsistent": "Fix-Level.",
        "help_level_cache": "Clean-Level.",
        "help_base": "Base/Root Prefix diagnostizieren.",
        "progress_envs": "Envs",
        "step_scan": "Scan",
        "step_snapshot": "Snapshot",
        "step_fix": "Fix",
        "step_adopt_pip": "Adopt-Pip",
        "adopt_search": "mamba search batch",
        "adopt_resolve": "adopt-pip resolve",
        "env_header": "== {name} ==",
        "path": "Pfad: {value}",
        "python": "Python: {value}",
        "channels": "Channels: {value}",
        "snapshot": "Snapshot: {path} {status}",
        "snapshot_ok": "ok",
        "snapshot_failed": "fehlgeschlagen",
        "issues_none": "Probleme: keine",
        "issues": "Probleme:",
        "pinned": "Pinned:",
        "fixes_none": "Fixes: keine",
        "fixes": "Fixes:",
        "issue_duplicate_dist_info": " - duplicate-dist-info: {package} {versions}",
        "issue_duplicate_pyd": " - duplicate-pyd: {base} {files}",
        "issue_invalid_artifact": " - invalid-artifact: {name}",
        "issue_generic": " - {type}",
        "fix_line": " - {label} {method} {status}",
        "fix_ok": "ok",
        "fix_failed": "fehlgeschlagen",
        "fix_report": "Fix-Report:",
        "fix_report_none": "keine Fixes ausgefuehrt",
        "col_action": "aktion",
        "col_item": "element",
        "col_result": "ergebnis",
        "col_reason": "grund",
        "reason_stale_artifact": "veraltetes/ungueltiges Artefakt in site-packages",
        "reason_duplicate_dist_info": "doppelte .dist-info Eintraege erkannt",
        "reason_conda_meta_reinstall": "defekte conda-meta Records (depends fehlt / JSON ungueltig)",
        "reason_case_conflict_pip_uninstall": "pip+conda haben gleiche Version mit unterschiedlicher Schreibweise installiert",
        "reason_case_conflict_conda_relink": "conda Paket nach pip-Uninstall erneut relinken",
        "reason_reinstall_duplicates": "Reinstall um Duplikate zu beheben",
        "reason_adopt_conda_install": "gemappte conda Pakete fuer pip-Kandidaten installieren",
        "reason_adopt_skip_keep": "{pip} behalten (pip {pip_version}), weil conda {conda} Version {conda_version} hat",
        "reason_adopt_pip_uninstall": "pip-Duplikate nach conda Install entfernen (nur wenn Versionen matchen)",
        "reason_adopt_pip_force_uninstall": "pip-Paket entfernen, weil conda-Ersatz bereits vorhanden ist",
        "reason_adopt_conda_relink": "conda Pakete nach pip-Uninstall erneut relinken",
    },
}


def detect_lang():
    # Best-effort auto-detection.
    for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
        val = os.environ.get(var)
        if isinstance(val, str) and val:
            if val.lower().startswith("de"):
                return "de"
            return "en"
    try:
        loc = locale.getdefaultlocale()[0]  # noqa: UP010 (keep compat)
    except Exception:
        loc = None
    if isinstance(loc, str) and loc.lower().startswith("de"):
        return "de"
    return "en"


def get_lang(lang):
    if not lang or lang == "auto":
        return detect_lang()
    if lang in MESSAGES:
        return lang
    return "en"


def t(key, *, lang, **kwargs):
    lang = get_lang(lang)
    msg = MESSAGES.get(lang, {}).get(key) or MESSAGES["en"].get(key) or key
    try:
        return msg.format(**kwargs)
    except Exception:
        return msg
