"""
Adaptateur de localisation pour l'interface graphique.
Toutes les traductions proviennent désormais des fichiers JSON
`web_sentinel/localization/{lang}.json`.
"""

from __future__ import annotations

import re
from types import SimpleNamespace
from typing import Any, Dict

from web_sentinel import localization as core_localization
from web_sentinel.localization import get_all_translations, get_translation_dict


class LocalizationManager:
    """Interface de localisation utilisée par l'interface graphique."""

    def set_language(self, language: str) -> None:
        core_localization.set_language(language)

    def get_language(self) -> str:
        return core_localization.get_current_language()

    def get_current_language(self) -> str:
        return self.get_language()

    @property
    def current_language(self) -> str:
        return self.get_language()

    @current_language.setter
    def current_language(self, value: str) -> None:
        self.set_language(value)

    @property
    def translations(self) -> Dict[str, Dict[str, Any]]:
        return get_all_translations()

    def get_available_languages(self) -> Dict[str, str]:
        return core_localization.get_available_languages()

    def t(self, key: str, *args: Any, **kwargs: Any) -> str:
        return core_localization.t(key, *args, **kwargs)

    def translate_severity(self, severity: str) -> str:
        return core_localization.translate_severity(severity)

    def translate_module(self, module: str) -> str:
        sanitized = module.replace("-", "_")
        alias_map = {
            "tls": "module_tls",
            "headers": "module_headers",
            "static": "module_static_analysis",
            "static_analysis": "module_static_analysis",
            "injection": "module_injection",
            "third_party": "module_third_party",
            "thirdparty": "module_third_party",
            "source_code": "module_source_code",
            "osint": "module_osint",
            "backend_config": "module_backend_config",
            "api_security": "module_api_security",
            "modern_web": "module_modern_web",
            "access_control": "module_access_control",
            "crypto_failures": "module_crypto_failures",
            "vulnerable_components": "module_vulnerable_components",
            "insecure_design": "module_insecure_design",
            "security_misconfiguration": "module_security_misconfig",
            "broken_authentication": "module_auth_failures",
        }
        key = alias_map.get(sanitized, f"module_{sanitized}")
        return core_localization.t(key)

    def translate_finding_content(self, finding: Any) -> Any:
        """Renvoie une copie traduite d'un finding."""
        if not hasattr(finding, "title") or not hasattr(finding, "description"):
            return finding

        translated = SimpleNamespace()
        for attr in dir(finding):
            if attr.startswith("_"):
                continue
            setattr(translated, attr, getattr(finding, attr))

        translation_key = getattr(finding, "i18n_key", None)
        params = getattr(finding, "i18n_params", {}) or {}

        if translation_key:
            entries = get_translation_dict(translation_key)
            for field, template in entries.items():
                if isinstance(template, str):
                    try:
                        value = template.format(**params)
                    except KeyError:
                        value = template
                    setattr(translated, field, value)

        self._apply_finding_heuristics(translated)
        return translated

    def _apply_finding_heuristics(self, finding: Any) -> None:
        """Ajustements heuristiques pour certaines traductions."""
        title = getattr(finding, "title", "") or ""
        description = getattr(finding, "description", "") or ""
        remediation = getattr(finding, "remediation", "") or ""

        current_language = self.current_language

        if current_language == "fr":
            finding.title = re.sub(r"ssl", "SSL", title, flags=re.IGNORECASE)
            finding.description = re.sub(r"ssl", "SSL", description, flags=re.IGNORECASE)
            finding.remediation = re.sub(r"ssl", "SSL", remediation, flags=re.IGNORECASE)
            return

        if current_language != "en":
            return

        title_lower = title.lower()

        if "certificat" in title_lower or "certificate" in title_lower:
            if "ssl" in title_lower:
                if any(token in title_lower for token in ["expiré", "expired", "expire"]):
                    days_match = re.search(r"(\d+)", title_lower)
                    if "expire" in title_lower and days_match:
                        days = days_match.group(1)
                        finding.title = f"SSL certificate expires in {days} days"
                        finding.description = (
                            "The SSL certificate for this host will expire soon."
                        )
                        finding.remediation = "Set up automatic certificate renewal."
                    else:
                        finding.title = "SSL certificate expired"
                        finding.description = (
                            "The SSL certificate for this host has expired."
                        )
                        finding.remediation = "Renew SSL certificate immediately."
                    return

        if "header" in title_lower or "en-tête" in title_lower:
            if any(token in title_lower for token in ["missing", "manquant"]):
                header_name = None
                if ":" in title:
                    header_name = title.split(":", 1)[1].strip()
                elif "missing" in title_lower:
                    match = re.search(
                        r"header\s*[:]?\s*([A-Za-z0-9-_.]+)", title, re.IGNORECASE
                    )
                    if match:
                        header_name = match.group(1)
                header_name = header_name or "security"
                finding.title = f"Security header missing: {header_name}"
                finding.description = f"The {header_name} security header is missing."
                finding.remediation = (
                    "Add the missing security header with an appropriate policy."
                )
                return


localization = LocalizationManager()

LocalizationAdapter = LocalizationManager
