"""Data access layer for ISO codes with full CRUD support and Chinese names."""

import os
import json
from typing import List, Optional, Dict, Any

DATABASE_DIR = os.path.join(os.path.dirname(__file__), "databases")


class Country:
    """ISO 3166-1 country data Data class representing a country with ISO codes and Chinese fields."""
    def __init__(self, **kwargs):
        # Map all raw JSON fields to object attributes
        self.alpha2 = kwargs.get("alpha_2", "").strip().upper()
        self.alpha3 = kwargs.get("alpha_3", "").strip().upper()
        self.name = kwargs.get("name", "").strip()
        self.official_name = kwargs.get("official_name", "").strip()
        self.numeric = kwargs.get("numeric", "").strip()
        self.flag = kwargs.get("flag", "").strip()
        self.chinese_name = kwargs.get("chinese_name", "").strip()

    def to_dict(self) -> Dict[str, Any]:
        """Convert country object back to dictionary for saving."""
        return {
            "alpha_2": self.alpha2,
            "alpha_3": self.alpha3,
            "name": self.name,
            "official_name": self.official_name,
            "numeric": self.numeric,
            "flag": self.flag,
            "chinese_name": self.chinese_name
        }

    def __repr__(self):
        return f"<Country {self.alpha2} {self.chinese_name}>"


class Countries:
    """ISO 3166-1 country data manager with full CRUD and lookup support."""

    def __init__(self):
        self.countries: List[Country] = []
        self._alpha2: Dict[str, Country] = {}
        self._alpha3: Dict[str, Country] = {}
        self._numeric: Dict[str, Country] = {}
        self._chinese_name: Dict[str, Country] = {}

        self._load()

    def _load(self) -> None:
        """Load countries from JSON database."""
        path = os.path.join(DATABASE_DIR, "iso_3166-1.json")
        if not os.path.exists(path):
            return

        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)

        for entry in data.get("3166-1", []):
            country = Country(**entry)
            self.countries.append(country)
            self._alpha2[country.alpha2] = country
            self._alpha3[country.alpha3] = country
            self._numeric[country.numeric] = country
            if country.chinese_name:
                self._chinese_name[country.chinese_name] = country

    # ====================== 查询（核心） ======================
    def get(
        self,
        *,
        alpha2: Optional[str] = None,
        alpha3: Optional[str] = None,
        numeric: Optional[str] = None,
        chinese_name: Optional[str] = None
    ) -> Optional[Country]:
        """
        Look up country by any key: alpha2 / alpha3 / numeric / chinese_name
        Returns None if not found.
        """
        if alpha2:
            return self._alpha2.get(alpha2.strip().upper())
        if alpha3:
            return self._alpha3.get(alpha3.strip().upper())
        if numeric:
            return self._numeric.get(numeric.strip())
        if chinese_name:
            return self._chinese_name.get(chinese_name.strip())
        return None

    # ====================== 增加 ======================
    def add(self, country: Country) -> None:
        """Add a new country (auto-update indexes)."""
        self.countries.append(country)
        self._alpha2[country.alpha2] = country
        self._alpha3[country.alpha3] = country
        self._numeric[country.numeric] = country
        if country.chinese_name:
            self._chinese_name[country.chinese_name] = country

    # ====================== 删除 ======================
    def remove(self, country: Country) -> None:
        """Remove a country object (auto-clean indexes)."""
        self.countries.remove(country)
        self._alpha2.pop(country.alpha2, None)
        self._alpha3.pop(country.alpha3, None)
        self._numeric.pop(country.numeric, None)
        self._chinese_name.pop(country.chinese_name, None)

    # ====================== 修改 ======================
    def update(self, old_country: Country, **fields) -> Optional[Country]:
        """Update country fields and refresh indexes."""
        self.remove(old_country)
        data = old_country.to_dict()
        data.update(fields)
        new_country = Country(**data)
        self.add(new_country)
        return new_country

    # ====================== 工具 ======================
    def list_all(self) -> List[Country]:
        """Return all countries."""
        return self.countries.copy()

    def clear(self):
        """Clear all data."""
        self.countries.clear()
        self._alpha2.clear()
        self._alpha3.clear()
        self._numeric.clear()
        self._chinese_name.clear()


countries = Countries()