<?php
declare(strict_types=1);

/**
 * 台灣縣市／鄉鎮市區／郵遞區號（FATE 內建，不依賴 newbies 或 spa.cities）。
 * 資料來源：fate/data/taiwan_zip3_by_city.json（3 碼郵遞區號，結構同常見開源 gist）。
 */

if (!function_exists('fate_taiwan_cities_json_path')) {
    function fate_taiwan_cities_json_path(): string
    {
        return dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'taiwan_zip3_by_city.json';
    }
}

if (!function_exists('fate_taiwan_cities_nested')) {
    /**
     * @return array<string, array<string, string>> 城市 => [地區 => 郵遞區號]
     */
    function fate_taiwan_cities_nested(): array
    {
        static $cache = null;
        if (is_array($cache)) {
            return $cache;
        }

        $path = fate_taiwan_cities_json_path();
        if (!is_file($path)) {
            throw new RuntimeException('找不到內建城市資料：' . $path);
        }

        $raw = file_get_contents($path);
        if ($raw === false || trim($raw) === '') {
            throw new RuntimeException('城市資料檔為空');
        }

        $decoded = json_decode($raw, true);
        if (!is_array($decoded)) {
            throw new RuntimeException('城市資料 JSON 格式錯誤');
        }

        $out = [];
        foreach ($decoded as $city => $districts) {
            if (!is_string($city) || $city === '' || !is_array($districts)) {
                continue;
            }
            $out[$city] = [];
            foreach ($districts as $district => $zip) {
                if (!is_string($district) || $district === '') {
                    continue;
                }
                $out[$city][$district] = is_string($zip) ? $zip : (string) $zip;
            }
        }

        if ($out === []) {
            throw new RuntimeException('城市資料沒有有效內容');
        }

        $cache = $out;

        return $cache;
    }
}

if (!function_exists('fate_taiwan_cities_list')) {
    /**
     * @return list<string>
     */
    function fate_taiwan_cities_list(): array
    {
        $nested = fate_taiwan_cities_nested();
        $cities = array_keys($nested);
        sort($cities, SORT_STRING);

        return $cities;
    }
}

if (!function_exists('fate_taiwan_districts_for_city')) {
    /**
     * @return list<array{district_name:string, zip_code:string}>
     */
    function fate_taiwan_districts_for_city(string $city): array
    {
        $city = trim($city);
        if ($city === '') {
            return [];
        }

        $nested = fate_taiwan_cities_nested();
        if (!isset($nested[$city])) {
            return [];
        }

        $rows = [];
        foreach ($nested[$city] as $district => $zip) {
            $rows[] = [
                'district_name' => $district,
                'zip_code' => $zip,
            ];
        }

        usort($rows, static function (array $a, array $b): int {
            return strcmp($a['district_name'], $b['district_name']);
        });

        return $rows;
    }
}
