"""Bangladesh delivery locations: Division → District → Area (upazila / thana).

Data: static/data/bd-locations.json (8 divisions, 64 districts, all upazilas from the
bangladesh-geocode dataset, plus Dhaka and Chattogram city thanas and city corporations).
The same file feeds the dropdowns in the browser."""
import json
from functools import lru_cache

from django.conf import settings


@lru_cache(maxsize=1)
def _data():
    path = settings.BASE_DIR / 'static' / 'data' / 'bd-locations.json'
    with open(path, encoding='utf-8') as fh:
        return json.load(fh)


@lru_cache(maxsize=1)
def _index():
    idx = {}
    for div in _data():
        for dist in div['d']:
            idx[(div['n'], dist['n'])] = {a[0]: a[1] for a in dist['a']}
    return idx


def divisions():
    return [(d['n'], d['b']) for d in _data()]


def is_valid(division, district, area):
    areas = _index().get((division, district))
    return bool(areas) and area in areas


def bangla(division, district, area):
    """Bangla names for display, falling back to English."""
    for div in _data():
        if div['n'] == division:
            for dist in div['d']:
                if dist['n'] == district:
                    return div['b'], dist['b'], {a[0]: a[1] for a in dist['a']}.get(area, area)
            return div['b'], district, area
    return division, district, area


def full_address(line, area, district, division):
    parts = [p.strip() for p in (line, area, district, division) if p and p.strip() and p != 'Other']
    return ', '.join(parts)
