# -*-coding:utf-8 -*-
import configparser
import os
import sys
from audioop import error


def get_config_paths():
    """返回所有可能的 config.ini 路径（按优先级排序）"""
    paths = []

    # 1. exe 同级目录（用户手动放置或外部修改）
    exe_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else None
    if exe_dir:
        paths.append(os.path.join(exe_dir, 'config.ini'))

    # 2. PyInstaller 资源目录 (_MEIPASS，打包时 datas 复制进来的)
    meipass = getattr(sys, '_MEIPASS', None)
    if meipass:
        paths.append(os.path.join(meipass, 'config.ini'))

    # 3. PubLibrary 目录下（优先查找）
    pub_dir = os.path.dirname(os.path.abspath(__file__))
    pub_path = os.path.join(pub_dir, 'config.ini')
    if pub_path not in paths:
        paths.append(pub_path)

    # 4. 项目根目录下（开发环境备用）
    project_root = os.path.dirname(pub_dir)
    root_path = os.path.join(project_root, 'config.ini')
    if root_path not in paths:
        paths.append(root_path)

    return paths


def IniWrite(section, keyname, value):
    exe_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else None
    base_dir = exe_dir if exe_dir else os.path.dirname(os.path.abspath(__file__))
    IniFileName = os.path.join(base_dir, 'config.ini')

    config = configparser.ConfigParser()
    try:
        with open(IniFileName, 'r', encoding='utf-8') as f:
            config.read_file(f)
    except FileNotFoundError:
        pass
    with open(IniFileName, 'w', encoding='utf-8') as configfile:
        if not config.has_section(section):
            config.add_section(section)
        config[section][keyname] = str(value)
        config.write(configfile)

def IniRead(section, key, default=None):
    fallback = default if default is not None else '5'

    for path in get_config_paths():
        if os.path.exists(path):
            try:
                config = configparser.ConfigParser()
                with open(path, 'r', encoding='utf-8') as f:
                    config.read_file(f)
                if config.has_section(section):
                    # print(f"[IniRead] 找到配置 [{section}] {key} -> {config[section][key]} (来源: {path})")
                    return config[section][key]
            except Exception as e:
                print(f"[IniRead] 读取失败 {path}: {e}")
    return fallback
