"""Zambia province and district data helpers."""
from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path

DATA_DIR = Path(__file__).resolve().parent / 'data'

# Legacy short province names used before the Province suffix was added.
ZAMBIA_REGION_CODES = {
    'Central Province': 'Central',
    'Copperbelt Province': 'Copperbelt',
    'Eastern Province': 'Eastern',
    'Luapula Province': 'Luapula',
    'Lusaka Province': 'Lusaka',
    'Muchinga Province': 'Muchinga',
    'Northern Province': 'Northern',
    'North-Western Province': 'Northwestern',
    'Southern Province': 'Southern',
    'Western Province': 'Western',
}

ZAMBIA_REGION_ALIASES = {
    'central': 'Central Province',
    'copperbelt': 'Copperbelt Province',
    'eastern': 'Eastern Province',
    'luapula': 'Luapula Province',
    'lusaka': 'Lusaka Province',
    'muchinga': 'Muchinga Province',
    'northern': 'Northern Province',
    'northwestern': 'North-Western Province',
    'north-western': 'North-Western Province',
    'north western': 'North-Western Province',
    'southern': 'Southern Province',
    'western': 'Western Province',
}


@lru_cache(maxsize=1)
def zambia_districts() -> dict[str, list[str]]:
    path = DATA_DIR / 'zambia_districts.json'
    return json.loads(path.read_text(encoding='utf-8'))


def normalize_zambia_region(region_name: str) -> str:
    region_name = (region_name or '').strip()
    if not region_name:
        return ''
    if region_name in ZAMBIA_REGION_CODES:
        return region_name
    alias = ZAMBIA_REGION_ALIASES.get(region_name.casefold())
    if alias:
        return alias
    if not region_name.endswith(' Province'):
        alias = ZAMBIA_REGION_ALIASES.get(region_name.casefold())
        return alias or region_name
    return region_name


def zambia_region_entries() -> list[dict[str, str]]:
    return [
        {'code': code, 'name': name}
        for name, code in ZAMBIA_REGION_CODES.items()
    ]
