#!/usr/bin/env python3
from __future__ import annotations

import json
import re
import sys
from pathlib import Path
from typing import Iterable, Dict, List
from urllib.parse import urlencode

import requests

REPO_ROOT = Path(__file__).resolve().parents[1]
CACHE_PATH = REPO_ROOT / 'artifacts' / 'team_name_zh_cache.json'

if str(REPO_ROOT / 'scripts') not in sys.path:
    sys.path.insert(0, str(REPO_ROOT / 'scripts'))

try:
    from generate_predictions_48h import TEAM_ZH as BUILTIN_TEAM_ZH  # type: ignore
except Exception:
    BUILTIN_TEAM_ZH = {}

EXTRA_TEAM_ZH: Dict[str, str] = {
    'Montedio Yamagata': '山形山神',
    'Vegalta Sendai': '仙台七夕',
    'Busan I Park': '釜山公园',
    'Gyeongnam FC': '庆南FC',
    'Gimpo Citizen': '金浦市民',
    'Daegu FC': '大邱FC',
    'Tochigi SC': '枥木SC',
    'Tochigi City': '枥木城',
    'Kagoshima United': '鹿儿岛联',
    'Renofa Yamaguchi': '山口雷法',
    'Kitakyushu': '北九州向日葵',
    'Kamatamare Sanuki': '赞岐釜玉海',
    'Nara Club': '奈良俱乐部',
    'Kanazawa': '金泽共进',
    'Osaka': '大阪FC',
    'Imabari': '今治FC',
    'Tokushima Vortis': '德岛漩涡',
    'Ehime FC': '爱媛FC',
    'Kochi United': '高知联',
    'Biwako Shiga': '滋贺琵琶湖',
    'Sagan Tosu': '鸟栖砂岩',
    'Hwaseong': '华城FC',
    'Yongin City': '龙仁市',
    'Philadelphia Union': '费城联合',
    'Inter Miami': '迈阿密国际',
    'New York City FC': '纽约城',
    'FC Tokyo': '东京足球俱乐部',
    'Tokyo Verdy': '东京绿茵',
    'Shimizu S-pulse': '清水心跳',
    'JEF United Chiba': '千叶市原',
    'Volos NFC': '沃洛斯',
    'PAOK': '塞萨洛尼基',
    'CF Montreal': '蒙特利尔',
    'Chapecoense-sc': '沙佩科恩斯',
    'AEK Athens FC': '雅典',
    'Sydney': '悉尼',
    'Kashima': '鹿岛鹿角',
    'Kawasaki Frontale': '川崎前锋',
    'Cerezo Osaka': '大阪樱花',
    'Kashiwa Reysol': '柏太阳神',
    'Urawa': '浦和红钻',
    'Perth Glory': '珀斯光荣',
    'FC Orenburg': '奥伦堡',
    'Newcastle': '纽卡斯尔联',
    'Preußen Münster': '普鲁士明斯特',
    'VfL Bochum': '波鸿',
    'Fortuna Düsseldorf': '杜塞尔多夫',
    'Dynamo': '莫斯科迪纳摩',
    'Krylia Sovetov': '苏维埃之翼',
    'Lyon': '里昂',
    'Tottenham': '托特纳姆热刺',
    'Aston Villa': '阿斯顿维拉',
    'Paris FC': '巴黎',
    'Marseille': '马赛',
    'Rennes': '雷恩',
    'FC Cincinnati': '辛辛那提',
    'Kyoto Sanga': '京都不死鸟',
    'Nagoya Grampus': '名古屋鲸鱼',
    'Sanfrecce Hiroshima': '广岛三箭',
    'Yokohama F. Marinos': '横滨水手',
    'Vissel Kobe': '神户胜利船',
    'Mito Hollyhock': '水户蜀葵',
    'Machida Zelvia': '町田泽维亚',
    'Melbourne City': '墨尔本城',
    'Spartak Moscow': '莫斯科斯巴达',
    'Sunderland': '桑德兰',
    '1. FC Magdeburg': '马格德堡',
    'Holstein Kiel': '荷尔斯泰因基尔',
    'Hertha BSC': '柏林赫塔',
    'Zenit': '泽尼特',
    'Rubin': '喀山红宝石',
    'Monaco': '摩纳哥',
    'Nottingham Forest': '诺丁汉森林',
    'West Ham': '西汉姆联',
    'Kifisia': '基菲西亚',
    'Celtic': '凯尔特人',
    'Dundee Utd': '邓迪联',
    'Nürnberg': '纽伦堡',
    'Porreres': '波雷雷斯',
    'Lugo': '卢戈',
    'Juventud': '尤文图德',
    'Albion FC': '阿尔比恩FC',
    'Boca Juniors': '博卡青年',
    'Real Murcia': '穆尔西亚',
    'Tarazona': '塔拉索纳',
    'Atletico Madrid W': '马德里竞技女足',
    'Real Madrid W': '皇家马德里女足',
    'Paris Saint Germain W': '巴黎圣日耳曼女足',
    'Montpellier W': '蒙彼利埃女足',
    'Birmingham City W': '伯明翰城女足',
    'Sheffield United W': '谢菲联女足',
    'Pachuca W': '帕丘卡女足',
    'Pumas UNAM W': '美洲狮女足',
    'Querétaro W': '克雷塔罗女足',
    'Tijuana W': '蒂华纳女足',
    'Eibar W': '埃瓦尔女足',
    'FC Koln W': '科隆女足',
    'Portsmouth W': '朴茨茅斯女足',
    'Sunderland W': '桑德兰女足',
    'Brighton U21': '布莱顿U21',
    'Everton U21': '埃弗顿U21',
}


def _load_cache(cache_path: Path = CACHE_PATH) -> Dict[str, str]:
    if cache_path.exists():
        try:
            data = json.loads(cache_path.read_text(encoding='utf-8'))
            if isinstance(data, dict):
                return {str(k): str(v) for k, v in data.items()}
        except Exception:
            pass
    return {}


def _save_cache(cache: Dict[str, str], cache_path: Path = CACHE_PATH) -> None:
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    cache_path.write_text(json.dumps(cache, ensure_ascii=False, indent=2), encoding='utf-8')


def _translate_batch(names: List[str]) -> Dict[str, str]:
    if not names:
        return {}
    text = '\n'.join(names)
    params = {
        'client': 'gtx',
        'sl': 'auto',
        'tl': 'zh-CN',
        'dt': 't',
        'q': text,
    }
    url = 'https://translate.googleapis.com/translate_a/single?' + urlencode(params)
    resp = requests.get(url, timeout=60)
    resp.raise_for_status()
    payload = resp.json()
    translated = ''.join(part[0] for part in payload[0]).split('\n')
    out: Dict[str, str] = {}
    for src, dst in zip(names, translated):
        out[src] = dst.strip() if dst and dst.strip() else src
    return out


def ensure_team_name_map(names: Iterable[str], cache_path: Path = CACHE_PATH, batch_size: int = 40) -> Dict[str, str]:
    cache = _load_cache(cache_path)
    combined: Dict[str, str] = {}
    combined.update(BUILTIN_TEAM_ZH)
    combined.update(cache)
    combined.update(EXTRA_TEAM_ZH)

    todo = []
    for raw in names:
        name = str(raw or '').strip()
        if not name:
            continue
        mapped = combined.get(name, '')
        if (not mapped) or (mapped == name) or re.search(r'[A-Za-z]', mapped):
            if name not in EXTRA_TEAM_ZH:
                todo.append(name)

    todo = list(dict.fromkeys(todo))
    for i in range(0, len(todo), batch_size):
        batch = todo[i:i + batch_size]
        translated = _translate_batch(batch)
        combined.update(translated)
        cache.update(translated)
    if todo:
        _save_cache(cache, cache_path)
    combined.update(EXTRA_TEAM_ZH)
    return combined


def to_zh(name: str, mapping: Dict[str, str] | None = None) -> str:
    s = str(name or '').strip()
    if not s:
        return s
    mp = mapping or ensure_team_name_map([s])
    return mp.get(s, s)
