"""
Base translation classes and utilities.

This module provides the foundation for the translation system,
including language enumeration and translation management.
"""

import json
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Optional


class Language(str, Enum):
    """Supported languages for PDF reports."""

    ENGLISH = "en"
    SPANISH = "es"

    @property
    def display_name(self) -> str:
        """Get the display name for the language."""
        return {
            self.ENGLISH: "English",
            self.SPANISH: "Español",
        }[self]


class TranslationManager:
    """Manages translations for PDF reports."""

    def __init__(self, base_path: Optional[Path] = None):
        """
        Initialize the translation manager.

        Args:
            base_path: Base path for translation files. If None, uses default.
        """
        if base_path is None:
            base_path = Path(__file__).parent / "locales"
        self.base_path = base_path
        self._cache: Dict[str, Dict[str, Any]] = {}

    def get_translation(self, language: Language, key: str, default: Optional[str] = None) -> str:
        """
        Get a translation for a specific language and key.

        Args:
            language: The target language
            key: The translation key (dot-separated path)
            default: Default value if translation not found

        Returns:
            The translated string
        """
        translations = self._load_language_file(language)

        # Navigate through nested keys
        value = translations
        for part in key.split("."):
            if isinstance(value, dict) and part in value:
                value = value[part]
            else:
                return default or key

        return str(value) if value is not None else (default or key)

    def _load_language_file(self, language: Language) -> Dict[str, Any]:
        """Load translation file for a language."""
        if language.value in self._cache:
            return self._cache[language.value]

        file_path = self.base_path / f"{language.value}.json"

        try:
            with open(file_path, "r", encoding="utf-8") as f:
                translations = json.load(f)
        except FileNotFoundError:
            translations = {}
        except json.JSONDecodeError:
            translations = {}

        self._cache[language.value] = translations
        return translations

    def get_template_path(self, base_template: str, language: Language) -> str:
        """
        Get the language-specific template path.

        Args:
            base_template: Base template path (e.g., "nassco/pacp/report.html")
            language: Target language

        Returns:
            Language-specific template path
        """
        if language == Language.ENGLISH:
            return base_template

        # For non-English languages, insert language code into path
        parts = base_template.split("/")
        if len(parts) >= 2:
            # Insert language code after the first part (e.g., nassco/pacp/es/report.html)
            parts.insert(2, language.value)
            return "/".join(parts)

        return base_template


# Global translation manager instance
translation_manager = TranslationManager()
