import json
import os


def load_jiancheng_data():
    """加载简称映射数据"""
    # 获取JianCheng.json文件路径
    jiancheng_path = os.path.join(
        os.path.dirname(os.path.dirname(__file__)),
        'Dict',
        'JianCheng.json'
    )

    try:
        with open(jiancheng_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"错误：找不到文件 {jiancheng_path}")
        return {}, {}
    except json.JSONDecodeError:
        print(f"错误：{jiancheng_path} 文件格式不正确")
        return {}, {}

    # 创建简称和全称映射字典
    abbrev_map = {}
    fullname_map = {}
    for item in data:
        abbrev = item.get('abbreviation')
        fullname = item.get('full_name')
        code = item.get('area_code')
        if abbrev and fullname and code:
            abbrev_map[abbrev] = {'full_name': fullname, 'area_code': code}
            fullname_map[fullname] = {'full_name': fullname, 'area_code': code}

    return abbrev_map, fullname_map


def load_yunnan_area_data():
    """加载云南省行政区划完整数据（非递归实现）"""
    area_path = os.path.join(
        os.path.dirname(os.path.dirname(__file__)),
        'Dict',
        '云南省行政区划数据.json'
    )

    try:
        with open(area_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"错误：找不到文件 {area_path}")
        return {}
    except json.JSONDecodeError:
        print(f"错误：{area_path} 文件格式不正确")
        return {}

    area_map = {}
    # 1. 添加省级数据
    province_name = data.get('name')
    province_code = data.get('code')
    if province_name and province_code:
        area_map[province_name] = {'full_name': province_name, 'area_code': province_code}

    # 2. 遍历城市和区县（非递归实现）
    citys = data.get('citys', [])
    for city in citys:
        # 添加城市数据
        city_name = city.get('name')
        city_code = city.get('code')
        if city_name and city_code:
            area_map[city_name] = {'full_name': city_name, 'area_code': city_code}

        # 添加区县数据
        areas = city.get('areas', [])
        for area in areas:
            area_name = area.get('name')
            area_code = area.get('code')
            if area_name and area_code:
                area_map[area_name] = {'full_name': area_name, 'area_code': area_code}

    return area_map


def query_area_info(query_str):
    """
    查询行政区划信息
    :param query_str: 简称或全称
    :return: 包含full_name和area_code的字典，未找到返回None
    """
    abbrev_map, fullname_map = load_jiancheng_data()
    yunnan_area_map = load_yunnan_area_data()
    
    # 1. 优先查询完整行政区划数据（最重要修正）
    if query_str in yunnan_area_map:
        return yunnan_area_map[query_str]
    
    # 2. 再查简称映射表（处理特殊名称）
    if query_str in abbrev_map:
        return abbrev_map[query_str]
    
    # 3. 最后查全称映射表+模糊匹配
    if query_str in fullname_map:
        return fullname_map[query_str]
    
    # 4. 模糊匹配保持不变
    for name, info in yunnan_area_map.items():
        if query_str in name or name in query_str:
            return info
    
    return None
