58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
"""Country display ownership for Earth comparisons and cards.
|
|
|
|
Keep source-country evidence separate; use this projection only for display
|
|
grouping so regional source records cannot become competing national keys.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
from app.core.countries import COUNTRY_ENTRIES, normalize_country
|
|
|
|
|
|
_DISPLAY_ISO_A3 = {
|
|
canonical: next(
|
|
(alias for alias in aliases if len(alias) == 3 and alias.isascii() and alias.isupper()),
|
|
None,
|
|
)
|
|
for canonical, aliases in COUNTRY_ENTRIES
|
|
}
|
|
_COUNTRY_BY_ISO_A3 = {code: country for country, code in _DISPLAY_ISO_A3.items() if code}
|
|
_POLICY_PATH = Path(__file__).resolve().parents[3] / "config/earth-boundary-pov-policy.china-v1.json"
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def _policy_country_by_code() -> dict[str, str]:
|
|
try:
|
|
content = _POLICY_PATH.read_text(encoding="utf-8")
|
|
except FileNotFoundError as error:
|
|
raise FileNotFoundError(f"EARTH_DISPLAY_POLICY_MISSING: {_POLICY_PATH}") from error
|
|
policy = json.loads(content)
|
|
if policy.get("profile") != "china-pov-v1":
|
|
raise ValueError("unsupported Earth display-policy profile")
|
|
mappings = {}
|
|
for rule in policy["rules"]:
|
|
target = rule.get("targetIsoA3") or rule.get("parentIsoA3")
|
|
if target not in _COUNTRY_BY_ISO_A3:
|
|
continue
|
|
for code in rule.get("sourceIsoA3", []):
|
|
mappings[code] = _COUNTRY_BY_ISO_A3[target]
|
|
return mappings
|
|
|
|
|
|
def display_country(value: str | None) -> str | None:
|
|
country = normalize_country(value)
|
|
code = _DISPLAY_ISO_A3.get(country) if country else str(value or "").strip().upper()
|
|
owner = _policy_country_by_code().get(code)
|
|
if owner:
|
|
return owner
|
|
return country
|
|
|
|
|
|
def display_iso_a3(value: str | None) -> str | None:
|
|
country = display_country(value)
|
|
return _DISPLAY_ISO_A3.get(country) if country else None
|