#!/usr/bin/env python3
"""
MixVideo V2 Python Core - Main Entry Point
用于PyInstaller打包的主入口文件
"""

import sys
import os
import argparse
import json
import traceback
from pathlib import Path

# 添加当前目录到Python路径，确保可以导入python_core模块
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

# 导入核心模块
try:
    from python_core.utils.logger import get_logger
    from python_core.utils.jsonrpc import create_response_handler, create_progress_reporter
    from python_core.config import get_config
except ImportError as e:
    print(f"ERROR: Failed to import core modules: {e}", file=sys.stderr)
    # 尝试备用导入方式
    try:
        import sys
        import os
        sys.path.insert(0, os.path.dirname(__file__))
        from utils.logger import get_logger
        from utils.jsonrpc import create_response_handler, create_progress_reporter
        from config import get_config
    except ImportError as e2:
        print(f"ERROR: Failed to import with backup method: {e2}", file=sys.stderr)
        sys.exit(1)

# 模块映射表
MODULE_MAP = {
    # 模板管理
    'template_manager': 'services.template_manager',
    'template': 'services.template_manager',
    
    # 项目管理
    'project_manager': 'services.project_manager',
    'project': 'services.project_manager',
    
    # 媒体管理
    'media_manager': 'services.media_manager',
    'media': 'services.media_manager',
    
    # 音频管理
    'audio_manager': 'services.audio_manager',
    'audio': 'services.audio_manager',
    
    # 模特管理
    'model_manager': 'services.model_manager',
    'model': 'services.model_manager',
    
    # 资源分类管理
    'resource_category_manager': 'services.resource_category_manager',
    'category': 'services.resource_category_manager',
    
    # 文件管理
    'file_manager': 'services.file_manager',
    'file': 'services.file_manager',
    
    # AI视频生成
    'ai_video': 'ai_video.video_generator',
    'video_generator': 'ai_video.video_generator',
    
    # 音频处理
    'audio_processing': 'audio_processing.core',
    
    # 视频处理
    'video_processing': 'video_processing.core',
}

def setup_logging():
    """设置日志"""
    try:
        logger = get_logger(__name__)
        return logger
    except Exception as e:
        print(f"WARNING: Failed to setup logging: {e}", file=sys.stderr)
        return None

def load_module_function(module_name, function_name):
    """动态加载模块和函数"""
    try:
        # 解析模块路径
        if module_name in MODULE_MAP:
            module_path = MODULE_MAP[module_name]
        else:
            module_path = module_name
        
        # 导入模块
        try:
            module = __import__(f"python_core.{module_path}", fromlist=[function_name])
        except ImportError:
            # 备用导入方式
            module = __import__(module_path, fromlist=[function_name])
        
        # 获取函数
        if hasattr(module, function_name):
            return getattr(module, function_name)
        else:
            raise AttributeError(f"Function '{function_name}' not found in module '{module_path}'")
            
    except ImportError as e:
        raise ImportError(f"Failed to import module '{module_path}': {e}")
    except Exception as e:
        raise Exception(f"Failed to load function '{function_name}' from '{module_path}': {e}")

def execute_action(module_name, action, params=None, progress_callback=None):
    """执行指定的动作"""
    logger = setup_logging()
    
    try:
        if logger:
            logger.info(f"Executing action: {module_name}.{action}")
        
        # 加载函数
        func = load_module_function(module_name, action)
        
        # 准备参数
        kwargs = {}
        if params:
            kwargs.update(params)
        
        # 添加进度回调
        if progress_callback:
            kwargs['progress_callback'] = progress_callback
        
        # 执行函数
        result = func(**kwargs)
        
        if logger:
            logger.info(f"Action completed successfully: {module_name}.{action}")
        
        return result
        
    except Exception as e:
        error_msg = f"Failed to execute {module_name}.{action}: {str(e)}"
        if logger:
            logger.error(error_msg)
            logger.error(traceback.format_exc())
        raise Exception(error_msg)

def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='MixVideo V2 Python Core')
    
    parser.add_argument('--module', '-m', required=True,
                       help='Module name (e.g., template_manager, project_manager)')
    
    parser.add_argument('--action', '-a', required=True,
                       help='Action to execute (e.g., get_templates, batch_import)')
    
    parser.add_argument('--params', '-p', type=str,
                       help='Parameters as JSON string')
    
    parser.add_argument('--config', '-c', type=str,
                       help='Configuration file path')
    
    parser.add_argument('--verbose', '-v', action='store_true',
                       help='Enable verbose logging')
    
    parser.add_argument('--version', action='version', version='MixVideo V2 Python Core 2.0.0')
    
    return parser.parse_args()

def main():
    """主函数"""
    try:
        # 解析参数
        args = parse_arguments()
        
        # 设置日志级别
        if args.verbose:
            os.environ['LOG_LEVEL'] = 'DEBUG'
        
        # 加载配置
        if args.config:
            os.environ['CONFIG_FILE'] = args.config
        
        # 解析参数
        params = {}
        if args.params:
            try:
                params = json.loads(args.params)
            except json.JSONDecodeError as e:
                print(f"ERROR: Invalid JSON parameters: {e}", file=sys.stderr)
                sys.exit(1)
        
        # 创建响应处理器
        send_response = create_response_handler()
        send_progress = create_progress_reporter()
        
        # 创建进度回调
        def progress_callback(step, progress, message, details=None):
            send_progress(step, progress, message, details or {})
        
        # 执行动作
        result = execute_action(args.module, args.action, params, progress_callback)
        
        # 发送成功响应
        send_response(True, "操作完成", result)
        
    except KeyboardInterrupt:
        print("ERROR: Operation cancelled by user", file=sys.stderr)
        sys.exit(130)
    except Exception as e:
        # 发送错误响应
        try:
            send_response = create_response_handler()
            send_response(False, str(e), None)
        except:
            print(f"ERROR: {str(e)}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
