#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
启动配置加载器
在主程序启动前加载配置文件中的设置
"""

import os
import sys
import configparser
from pathlib import Path

def load_startup_config():
    """加载启动配置并设置环境变量"""
    try:
        # 获取配置文件路径
        if getattr(sys, 'frozen', False):
            # 在打包后的可执行文件中
            app_dir = Path(sys.executable).parent
        else:
            # 在开发环境中
            app_dir = Path(__file__).parent.parent.parent
        
        config_file = app_dir / "config.ini"
        
        if config_file.exists():
            config = configparser.ConfigParser()
            config.read(str(config_file), encoding='utf-8')
            
            # 加载数据库配置
            if 'database' in config:
                db_config = config['database']
                if 'username' in db_config:
                    os.environ['DB_USER'] = db_config['username']
                if 'password' in db_config:
                    os.environ['DB_PASSWORD'] = db_config['password']
                if 'host' in db_config:
                    os.environ['DB_HOST'] = db_config['host']
            
            # 加载API配置
            if 'api' in config:
                api_config = config['api']
                if 'tf_api_base_url' in api_config:
                    os.environ['TF_API_BASE_URL'] = api_config['tf_api_base_url']
                if 'tf_web_post' in api_config:
                    os.environ['TF_WEB_POST'] = api_config['tf_web_post']
                if 'cm_id' in api_config:
                    os.environ['CM_ID'] = api_config['cm_id']
                if 'dg_id' in api_config:
                    os.environ['DG_ID'] = api_config['dg_id']
            
            print(f"配置已从 {config_file} 加载")
            return True
        else:
            print(f"配置文件不存在: {config_file}")
            return False
            
    except Exception as e:
        print(f"加载配置失败: {e}")
        return False

def ensure_config_exists():
    """确保配置文件存在，如果不存在则创建默认配置"""
    try:
        if getattr(sys, 'frozen', False):
            app_dir = Path(sys.executable).parent
        else:
            app_dir = Path(__file__).parent.parent.parent
        
        config_file = app_dir / "config.ini"
        
        if not config_file.exists():
            config = configparser.ConfigParser()
            
            # 默认数据库配置
            config['database'] = {
                'username': 'root',
                'password': 'root',
                'host': 'localhost'
            }
            
            # 创建配置内容，包含注释
            config_content = """[database]
username = root
password = root
host = localhost

[api]
tf_api_base_url = http://111.231.146.230:4080/jeecg-boot
tf_web_post = false
cm_id = 571985c1-cfa5-4186-8acd-6e3868a5e08c
dg_id = e22cacb4-a580-45ba-949e-356f57fa1a43
"""
            
            with open(str(config_file), 'w', encoding='utf-8') as f:
                f.write(config_content)
            
            print(f"已创建默认配置文件: {config_file}")
    
    except Exception as e:
        print(f"创建默认配置失败: {e}")

if __name__ == "__main__":
    ensure_config_exists()
    load_startup_config()