from typing import List
import configparser
from pathlib import Path
import sys

miniQMTPath = r'D:\\Programs\\DTQMT\\userdata_mini' # miniQMT软件的安装路径
# miniQMTPath = ''
account_no:str = '99082560'
console_log = True
log_level = "INFO"

def get_config_path() -> Path:
    """获取配置文件的正确路径（兼容开发环境和打包后的可执行文件）"""
    if getattr(sys, 'frozen', False):
        # 打包后的可执行文件环境
        # sys._MEIPASS是PyInstaller解压临时文件的目录
        # 配置文件应该放在可执行文件同目录下
        base_path = Path(sys.executable).parent
    else:
        # 开发环境
        base_path = Path(__file__).resolve().parent
    
    return base_path / 'config.ini'

def save_config(miniQmtPath:str, account_no:str):
    """创建默认配置文件"""
    config = configparser.ConfigParser()
    config['config'] = {
        'miniQMTPath': miniQmtPath,
        'account_no': account_no
    }
    config_path = get_config_path()
    with open(config_path, 'w') as configfile:
        config.write(configfile)
    print(f'已创建默认配置文件: {config_path}')

def exist_config() -> bool:
    """检查配置文件是否存在"""
    config_path = get_config_path()
    return config_path.exists()

def initConfig() -> bool:
    global miniQMTPath, account_no
    
    # 获取配置文件路径
    config_path = get_config_path()
    
    config = configparser.ConfigParser()
    config.read(config_path, encoding='utf-8')
    miniQMTPath = config.get('config','miniQMTPath')
    account_no = config.get('config','account_no')

    # 判断miniQMTPath是否为空，并且目录是否存在
    if not miniQMTPath or not Path(miniQMTPath).exists():
        print('请先配置miniQMTPath')
        return False
    else:
        return True
