"""ISO 4217 currency codes for forms and model validation."""

from __future__ import annotations

from pathlib import Path

_DEFAULT_CURRENCY = "USD"


def _load_iso4217() -> tuple[tuple[str, str], ...]:
    path = Path(__file__).with_name("iso4217.tsv")
    rows: list[tuple[str, str]] = []
    with path.open(encoding="utf-8") as handle:
        first = handle.readline()
        if not first.lower().startswith("code"):
            raise ValueError("iso4217.tsv must start with header: code\tname")
        for raw in handle:
            line = raw.strip()
            if not line:
                continue
            parts = line.split("\t", 1)
            if len(parts) != 2:
                continue
            code, name = parts[0].strip().upper(), parts[1].strip()
            if len(code) != 3:
                continue
            rows.append((code, f"{code} — {name}"))
    rows.sort(key=lambda r: r[0])
    return tuple(rows)


ISO4217_CHOICES: tuple[tuple[str, str], ...] = _load_iso4217()
ISO4217_CODES: frozenset[str] = frozenset(c for c, _ in ISO4217_CHOICES)
DEFAULT_CURRENCY: str = _DEFAULT_CURRENCY


def is_valid_currency(code: str) -> bool:
    return (code or "").strip().upper() in ISO4217_CODES
