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

"""
Travel Content Creator API v2 Startup Script
旅游内容创作API v2 启动脚本
"""

import os
import sys
import logging
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def setup_logging(log_level: str = "INFO"):
    """设置日志配置"""
    log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format=log_format,
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler('api_v2.log', encoding='utf-8')
        ]
    )

def check_environment():
    """检查环境配置"""
    required_env_vars = [
        'AI_API_KEY',
    ]
    
    missing_vars = []
    for var in required_env_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    if missing_vars:
        print(f"⚠️  警告: 缺少环境变量: {', '.join(missing_vars)}")
        print("请在 .env 文件中设置这些变量或通过环境变量传递")
        
        # 提供默认值建议
        env_examples = {
            'AI_API_KEY': 'your_ai_api_key_here',
            'AI_BASE_URL': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
            'AI_MODEL': 'qwen-plus'
        }
        
        print("\n示例 .env 文件内容:")
        for var, example in env_examples.items():
            print(f"{var}={example}")

def check_dependencies():
    """检查依赖项"""
    try:
        import fastapi
        import uvicorn
        import pydantic
        print("✅ 基础依赖检查通过")
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("请运行: pip install -r requirements.txt")
        sys.exit(1)
    
    # 检查算法包
    try:
        sys.path.insert(0, str(project_root / "travel-algorithms"))
        import travel_algorithms
        print("✅ 算法包检查通过")
    except ImportError as e:
        print(f"❌ 算法包导入失败: {e}")
        print("请确保 travel-algorithms 包已正确安装")
        print("运行: cd travel-algorithms && pip install -e .")
        sys.exit(1)

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Travel Content Creator API v2')
    parser.add_argument('--host', default='0.0.0.0', help='服务器地址')
    parser.add_argument('--port', type=int, default=8000, help='服务器端口')
    parser.add_argument('--reload', action='store_true', help='开发模式（自动重载）')
    parser.add_argument('--log-level', default='INFO', 
                       choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
                       help='日志级别')
    parser.add_argument('--workers', type=int, default=1, help='工作进程数量')
    parser.add_argument('--check-only', action='store_true', help='仅检查环境，不启动服务')
    
    args = parser.parse_args()
    
    # 设置日志
    setup_logging(args.log_level)
    logger = logging.getLogger(__name__)
    
    print("🚀 Travel Content Creator API v2")
    print("=" * 50)
    
    # 检查环境
    logger.info("检查运行环境...")
    check_environment()
    check_dependencies()
    
    if args.check_only:
        print("✅ 环境检查完成")
        return
    
    # 设置环境变量
    os.environ.setdefault('PORT', str(args.port))
    
    # 启动服务器
    try:
        import uvicorn
        
        logger.info(f"启动API服务器...")
        print(f"🌐 服务地址: http://{args.host}:{args.port}")
        print(f"📚 API文档: http://{args.host}:{args.port}/docs")
        print(f"🔧 健康检查: http://{args.host}:{args.port}/health")
        print("=" * 50)
        
        # 构建uvicorn配置
        uvicorn_config = {
            "app": "api_v2.main:app",
            "host": args.host,
            "port": args.port,
            "log_level": args.log_level.lower(),
            "access_log": True,
        }
        
        if args.reload:
            uvicorn_config["reload"] = True
            uvicorn_config["reload_dirs"] = [str(project_root)]
        else:
            uvicorn_config["workers"] = args.workers
        
        uvicorn.run(**uvicorn_config)
        
    except KeyboardInterrupt:
        logger.info("收到中断信号，正在关闭服务器...")
        print("\n👋 服务器已关闭")
    except Exception as e:
        logger.error(f"启动失败: {e}", exc_info=True)
        sys.exit(1)

if __name__ == "__main__":
    main() 