#!/usr/bin/env python3
"""
全国行政区划数据初始化脚本
数据来源：基于GB/T 2260标准
包含：31个省/直辖市/自治区 + 主要地级市
"""

import json
import asyncio
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))

from app.core.database import get_pool, get_system_pool, _has_split_databases
from app.core.cache import get_redis
import aiomysql

REGION_TREE_CACHE_KEY = "bff:region:tree"
REGION_TREE_CACHE_TTL = 3600

# 全国31个省/直辖市/自治区行政区划数据
CHINA_REGIONS = {
    "id": "root",
    "name": "中国",
    "path": "/中国",
    "level": "country",
    "children": [
        {
            "id": "beijing",
            "name": "北京市",
            "path": "/中国/北京市",
            "level": "province",
            "children": [
                {"id": "beijing_dongcheng", "name": "东城区", "path": "/中国/北京市/东城区", "level": "district", "children": []},
                {"id": "beijing_xicheng", "name": "西城区", "path": "/中国/北京市/西城区", "level": "district", "children": []},
                {"id": "beijing_chaoyang", "name": "朝阳区", "path": "/中国/北京市/朝阳区", "level": "district", "children": []},
                {"id": "beijing_haidian", "name": "海淀区", "path": "/中国/北京市/海淀区", "level": "district", "children": []},
            ]
        },
        {
            "id": "tianjin",
            "name": "天津市",
            "path": "/中国/天津市",
            "level": "province",
            "children": [
                {"id": "tianjin_heping", "name": "和平区", "path": "/中国/天津市/和平区", "level": "district", "children": []},
                {"id": "tianjin_hexi", "name": "河西区", "path": "/中国/天津市/河西区", "level": "district", "children": []},
                {"id": "tianjin_nankai", "name": "南开区", "path": "/中国/天津市/南开区", "level": "district", "children": []},
            ]
        },
        {
            "id": "hebei",
            "name": "河北省",
            "path": "/中国/河北省",
            "level": "province",
            "children": [
                {"id": "shijiazhuang", "name": "石家庄市", "path": "/中国/河北省/石家庄市", "level": "city", "children": []},
                {"id": "tangshan", "name": "唐山市", "path": "/中国/河北省/唐山市", "level": "city", "children": []},
                {"id": "baoding", "name": "保定市", "path": "/中国/河北省/保定市", "level": "city", "children": []},
                {"id": "langfang", "name": "廊坊市", "path": "/中国/河北省/廊坊市", "level": "city", "children": []},
            ]
        },
        {
            "id": "shanxi",
            "name": "山西省",
            "path": "/中国/山西省",
            "level": "province",
            "children": [
                {"id": "taiyuan", "name": "太原市", "path": "/中国/山西省/太原市", "level": "city", "children": []},
                {"id": "datong", "name": "大同市", "path": "/中国/山西省/大同市", "level": "city", "children": []},
            ]
        },
        {
            "id": "neimenggu",
            "name": "内蒙古自治区",
            "path": "/中国/内蒙古自治区",
            "level": "province",
            "children": [
                {"id": "huhehaote", "name": "呼和浩特市", "path": "/中国/内蒙古自治区/呼和浩特市", "level": "city", "children": []},
                {"id": "baotou", "name": "包头市", "path": "/中国/内蒙古自治区/包头市", "level": "city", "children": []},
            ]
        },
        {
            "id": "liaoning",
            "name": "辽宁省",
            "path": "/中国/辽宁省",
            "level": "province",
            "children": [
                {"id": "shenyang", "name": "沈阳市", "path": "/中国/辽宁省/沈阳市", "level": "city", "children": []},
                {"id": "dalian", "name": "大连市", "path": "/中国/辽宁省/大连市", "level": "city", "children": []},
            ]
        },
        {
            "id": "jilin",
            "name": "吉林省",
            "path": "/中国/吉林省",
            "level": "province",
            "children": [
                {"id": "changchun", "name": "长春市", "path": "/中国/吉林省/长春市", "level": "city", "children": []},
                {"id": "jilin_city", "name": "吉林市", "path": "/中国/吉林省/吉林市", "level": "city", "children": []},
            ]
        },
        {
            "id": "heilongjiang",
            "name": "黑龙江省",
            "path": "/中国/黑龙江省",
            "level": "province",
            "children": [
                {"id": "haerbin", "name": "哈尔滨市", "path": "/中国/黑龙江省/哈尔滨市", "level": "city", "children": []},
                {"id": "qiqihaer", "name": "齐齐哈尔市", "path": "/中国/黑龙江省/齐齐哈尔市", "level": "city", "children": []},
            ]
        },
        {
            "id": "shanghai",
            "name": "上海市",
            "path": "/中国/上海市",
            "level": "province",
            "children": [
                {"id": "shanghai_huangpu", "name": "黄浦区", "path": "/中国/上海市/黄浦区", "level": "district", "children": []},
                {"id": "shanghai_jingan", "name": "静安区", "path": "/中国/上海市/静安区", "level": "district", "children": []},
                {"id": "shanghai_xuhui", "name": "徐汇区", "path": "/中国/上海市/徐汇区", "level": "district", "children": []},
                {"id": "shanghai_pudong", "name": "浦东新区", "path": "/中国/上海市/浦东新区", "level": "district", "children": []},
            ]
        },
        {
            "id": "jiangsu",
            "name": "江苏省",
            "path": "/中国/江苏省",
            "level": "province",
            "children": [
                {"id": "nanjing", "name": "南京市", "path": "/中国/江苏省/南京市", "level": "city", "children": []},
                {"id": "suzhou", "name": "苏州市", "path": "/中国/江苏省/苏州市", "level": "city", "children": []},
                {"id": "wuxi", "name": "无锡市", "path": "/中国/江苏省/无锡市", "level": "city", "children": []},
                {"id": "changzhou", "name": "常州市", "path": "/中国/江苏省/常州市", "level": "city", "children": []},
            ]
        },
        {
            "id": "zhejiang",
            "name": "浙江省",
            "path": "/中国/浙江省",
            "level": "province",
            "children": [
                {"id": "hangzhou", "name": "杭州市", "path": "/中国/浙江省/杭州市", "level": "city", "children": []},
                {"id": "ningbo", "name": "宁波市", "path": "/中国/浙江省/宁波市", "level": "city", "children": []},
                {"id": "wenzhou", "name": "温州市", "path": "/中国/浙江省/温州市", "level": "city", "children": []},
            ]
        },
        {
            "id": "anhui",
            "name": "安徽省",
            "path": "/中国/安徽省",
            "level": "province",
            "children": [
                {"id": "hefei", "name": "合肥市", "path": "/中国/安徽省/合肥市", "level": "city", "children": []},
                {"id": "wuhu", "name": "芜湖市", "path": "/中国/安徽省/芜湖市", "level": "city", "children": []},
            ]
        },
        {
            "id": "fujian",
            "name": "福建省",
            "path": "/中国/福建省",
            "level": "province",
            "children": [
                {"id": "fuzhou", "name": "福州市", "path": "/中国/福建省/福州市", "level": "city", "children": []},
                {"id": "xiamen", "name": "厦门市", "path": "/中国/福建省/厦门市", "level": "city", "children": []},
                {"id": "quanzhou", "name": "泉州市", "path": "/中国/福建省/泉州市", "level": "city", "children": []},
                {"id": "zhangzhou", "name": "漳州市", "path": "/中国/福建省/漳州市", "level": "city", "children": []},
            ]
        },
        {
            "id": "jiangxi",
            "name": "江西省",
            "path": "/中国/江西省",
            "level": "province",
            "children": [
                {"id": "nanchang", "name": "南昌市", "path": "/中国/江西省/南昌市", "level": "city", "children": []},
                {"id": "jiujiang", "name": "九江市", "path": "/中国/江西省/九江市", "level": "city", "children": []},
            ]
        },
        {
            "id": "shandong",
            "name": "山东省",
            "path": "/中国/山东省",
            "level": "province",
            "children": [
                {"id": "jinan", "name": "济南市", "path": "/中国/山东省/济南市", "level": "city", "children": []},
                {"id": "qingdao", "name": "青岛市", "path": "/中国/山东省/青岛市", "level": "city", "children": []},
                {"id": "yantai", "name": "烟台市", "path": "/中国/山东省/烟台市", "level": "city", "children": []},
            ]
        },
        {
            "id": "henan",
            "name": "河南省",
            "path": "/中国/河南省",
            "level": "province",
            "children": [
                {"id": "zhengzhou", "name": "郑州市", "path": "/中国/河南省/郑州市", "level": "city", "children": []},
                {"id": "luoyang", "name": "洛阳市", "path": "/中国/河南省/洛阳市", "level": "city", "children": []},
            ]
        },
        {
            "id": "hubei",
            "name": "湖北省",
            "path": "/中国/湖北省",
            "level": "province",
            "children": [
                {"id": "wuhan", "name": "武汉市", "path": "/中国/湖北省/武汉市", "level": "city", "children": []},
                {"id": "yichang", "name": "宜昌市", "path": "/中国/湖北省/宜昌市", "level": "city", "children": []},
            ]
        },
        {
            "id": "hunan",
            "name": "湖南省",
            "path": "/中国/湖南省",
            "level": "province",
            "children": [
                {"id": "changsha", "name": "长沙市", "path": "/中国/湖南省/长沙市", "level": "city", "children": []},
                {"id": "zhuzhou", "name": "株洲市", "path": "/中国/湖南省/株洲市", "level": "city", "children": []},
            ]
        },
        {
            "id": "guangdong",
            "name": "广东省",
            "path": "/中国/广东省",
            "level": "province",
            "children": [
                {"id": "guangzhou", "name": "广州市", "path": "/中国/广东省/广州市", "level": "city", "children": []},
                {"id": "shenzhen", "name": "深圳市", "path": "/中国/广东省/深圳市", "level": "city", "children": []},
                {"id": "zhuhai", "name": "珠海市", "path": "/中国/广东省/珠海市", "level": "city", "children": []},
                {"id": "foshan", "name": "佛山市", "path": "/中国/广东省/佛山市", "level": "city", "children": []},
            ]
        },
        {
            "id": "guangxi",
            "name": "广西壮族自治区",
            "path": "/中国/广西壮族自治区",
            "level": "province",
            "children": [
                {"id": "nanning", "name": "南宁市", "path": "/中国/广西壮族自治区/南宁市", "level": "city", "children": []},
                {"id": "guilin", "name": "桂林市", "path": "/中国/广西壮族自治区/桂林市", "level": "city", "children": []},
            ]
        },
        {
            "id": "hainan",
            "name": "海南省",
            "path": "/中国/海南省",
            "level": "province",
            "children": [
                {"id": "haikou", "name": "海口市", "path": "/中国/海南省/海口市", "level": "city", "children": []},
                {"id": "sanya", "name": "三亚市", "path": "/中国/海南省/三亚市", "level": "city", "children": []},
            ]
        },
        {
            "id": "chongqing",
            "name": "重庆市",
            "path": "/中国/重庆市",
            "level": "province",
            "children": [
                {"id": "chongqing_yuzhong", "name": "渝中区", "path": "/中国/重庆市/渝中区", "level": "district", "children": []},
                {"id": "chongqing_jiangbei", "name": "江北区", "path": "/中国/重庆市/江北区", "level": "district", "children": []},
            ]
        },
        {
            "id": "sichuan",
            "name": "四川省",
            "path": "/中国/四川省",
            "level": "province",
            "children": [
                {"id": "chengdu", "name": "成都市", "path": "/中国/四川省/成都市", "level": "city", "children": []},
                {"id": "mianyang", "name": "绵阳市", "path": "/中国/四川省/绵阳市", "level": "city", "children": []},
            ]
        },
        {
            "id": "guizhou",
            "name": "贵州省",
            "path": "/中国/贵州省",
            "level": "province",
            "children": [
                {"id": "guiyang", "name": "贵阳市", "path": "/中国/贵州省/贵阳市", "level": "city", "children": []},
                {"id": "zunyi", "name": "遵义市", "path": "/中国/贵州省/遵义市", "level": "city", "children": []},
            ]
        },
        {
            "id": "yunnan",
            "name": "云南省",
            "path": "/中国/云南省",
            "level": "province",
            "children": [
                {"id": "kunming", "name": "昆明市", "path": "/中国/云南省/昆明市", "level": "city", "children": []},
                {"id": "dali", "name": "大理市", "path": "/中国/云南省/大理市", "level": "city", "children": []},
            ]
        },
        {
            "id": "xizang",
            "name": "西藏自治区",
            "path": "/中国/西藏自治区",
            "level": "province",
            "children": [
                {"id": "lasa", "name": "拉萨市", "path": "/中国/西藏自治区/拉萨市", "level": "city", "children": []},
            ]
        },
        {
            "id": "shaanxi",
            "name": "陕西省",
            "path": "/中国/陕西省",
            "level": "province",
            "children": [
                {"id": "xian", "name": "西安市", "path": "/中国/陕西省/西安市", "level": "city", "children": []},
                {"id": "baoji", "name": "宝鸡市", "path": "/中国/陕西省/宝鸡市", "level": "city", "children": []},
            ]
        },
        {
            "id": "gansu",
            "name": "甘肃省",
            "path": "/中国/甘肃省",
            "level": "province",
            "children": [
                {"id": "lanzhou", "name": "兰州市", "path": "/中国/甘肃省/兰州市", "level": "city", "children": []},
            ]
        },
        {
            "id": "qinghai",
            "name": "青海省",
            "path": "/中国/青海省",
            "level": "province",
            "children": [
                {"id": "xining", "name": "西宁市", "path": "/中国/青海省/西宁市", "level": "city", "children": []},
            ]
        },
        {
            "id": "ningxia",
            "name": "宁夏回族自治区",
            "path": "/中国/宁夏回族自治区",
            "level": "province",
            "children": [
                {"id": "yinchuan", "name": "银川市", "path": "/中国/宁夏回族自治区/银川市", "level": "city", "children": []},
            ]
        },
        {
            "id": "xinjiang",
            "name": "新疆维吾尔自治区",
            "path": "/中国/新疆维吾尔自治区",
            "level": "province",
            "children": [
                {"id": "urumqi", "name": "乌鲁木齐市", "path": "/中国/新疆维吾尔自治区/乌鲁木齐市", "level": "city", "children": []},
                {"id": "kashgar", "name": "喀什地区", "path": "/中国/新疆维吾尔自治区/喀什地区", "level": "city", "children": []},
            ]
        },
        {
            "id": "taiwan",
            "name": "台湾省",
            "path": "/中国/台湾省",
            "level": "province",
            "children": [
                {"id": "taipei", "name": "台北市", "path": "/中国/台湾省/台北市", "level": "city", "children": []},
            ]
        },
        {
            "id": "hongkong",
            "name": "香港特别行政区",
            "path": "/中国/香港特别行政区",
            "level": "province",
            "children": [
                {"id": "hongkong_central", "name": "中西区", "path": "/中国/香港特别行政区/中西区", "level": "district", "children": []},
            ]
        },
        {
            "id": "macau",
            "name": "澳门特别行政区",
            "path": "/中国/澳门特别行政区",
            "level": "province",
            "children": [
                {"id": "macau_se", "name": "花地玛堂区", "path": "/中国/澳门特别行政区/花地玛堂区", "level": "district", "children": []},
            ]
        },
    ]
}


async def init_regions():
    """初始化全国行政区划数据到数据库"""
    print("开始初始化全国行政区划数据...")
    
    try:
        pool = await get_system_pool() if _has_split_databases() else await get_pool()
        async with pool.acquire() as conn:
            async with conn.cursor() as cur:
                # 检查是否已存在数据
                await cur.execute(
                    "SELECT COUNT(*) as count FROM system_configs WHERE config_key = 'region.tree'"
                )
                row = await cur.fetchone()
                
                if row and row[0] > 0:
                    print("行政区划数据已存在，是否覆盖？(y/n): ", end="")
                    # 在非交互环境下默认不覆盖
                    import sys
                    if not sys.stdin.isatty():
                        print("非交互环境，跳过覆盖")
                        return
                    
                    response = input().strip().lower()
                    if response != 'y':
                        print("已取消初始化")
                        return
                
                # 插入/更新数据
                tree_json = json.dumps(CHINA_REGIONS, ensure_ascii=False)
                await cur.execute(
                    """INSERT INTO system_configs (config_key, config_value, config_type, category, description) 
                       VALUES ('region.tree', %s, 'json', 'region', '全国行政区划树形结构')
                       ON DUPLICATE KEY UPDATE config_value = %s""",
                    (tree_json, tree_json)
                )
                await conn.commit()
                
                # 更新Redis缓存
                r = await get_redis()
                try:
                    await r.setex(REGION_TREE_CACHE_KEY, REGION_TREE_CACHE_TTL, tree_json)
                except Exception as e:
                    print(f"Redis缓存更新失败: {e}")
                
                # 统计信息
                province_count = len(CHINA_REGIONS["children"])
                city_count = sum(len(p.get("children", [])) for p in CHINA_REGIONS["children"])
                
                print(f"✅ 行政区划数据初始化成功！")
                print(f"   - 省级行政区: {province_count} 个")
                print(f"   - 地市级行政区: {city_count} 个")
                print(f"   - 数据已保存到数据库和Redis缓存")
                
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        raise


async def clear_regions():
    """清空行政区划数据"""
    print("开始清空行政区划数据...")
    
    try:
        pool = await get_system_pool() if _has_split_databases() else await get_pool()
        async with pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(
                    "DELETE FROM system_configs WHERE config_key = 'region.tree'"
                )
                await conn.commit()
                
                # 清除Redis缓存
                r = await get_redis()
                try:
                    await r.delete(REGION_TREE_CACHE_KEY)
                except Exception:
                    pass
                
                print("✅ 行政区划数据已清空")
                
    except Exception as e:
        print(f"❌ 清空失败: {e}")
        raise


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="行政区划数据管理工具")
    parser.add_argument("action", choices=["init", "clear"], help="操作类型: init=初始化, clear=清空")
    
    args = parser.parse_args()
    
    if args.action == "init":
        asyncio.run(init_regions())
    elif args.action == "clear":
        asyncio.run(clear_regions())
