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

"""
带配置加载的主程序入口
在原有app.py基础上，添加启动时配置加载功能
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
if getattr(sys, 'frozen', False):
    # 打包后的环境
    project_root = Path(sys.executable).parent
else:
    # 开发环境
    project_root = Path(__file__).parent.parent

sys.path.insert(0, str(project_root))

# 导入配置加载器
try:
    from packaging.config_tool.startup_loader import load_startup_config, ensure_config_exists
    
    # 确保配置文件存在
    ensure_config_exists()
    
    # 加载配置
    load_startup_config()
    print("配置加载完成")
    
except ImportError as e:
    print(f"警告: 无法导入配置加载器: {e}")
except Exception as e:
    print(f"警告: 配置加载失败: {e}")

# 现在导入并运行原始的app.py
try:
    from app import *
    
    # 如果是直接运行此脚本，则启动服务
    if __name__ == "__main__":
        import time
        port = 8000
        
        # 导入日志工具
        from utils.logger import get_logger
        logger = get_logger("main")
        
        logger.info(f"服务器配置 - Host: 0.0.0.0, Port: {port}, Workers: {settings.SERVER_WORKERS}, Reload: {settings.SERVER_RELOAD}")
        
        # 启动服务器
        import uvicorn
        uvicorn.run(
            "app:app",
            host="0.0.0.0",
            port=port,
            reload=settings.SERVER_RELOAD,
            workers=settings.SERVER_WORKERS
        )

except ImportError as e:
    print(f"错误: 无法导入主程序: {e}")
    sys.exit(1)
except Exception as e:
    print(f"错误: 程序启动失败: {e}")
    sys.exit(1)