#!/usr/bin/env python3
"""
MixVideo V2 Python Core - 功能版入口文件
支持实际的模块调用和功能执行
"""

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))
sys.path.insert(0, str(current_dir.parent))

# 模块映射表
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',

    # 测试模块
    'test': 'test_module',
}

def setup_logging():
    """设置日志"""
    try:
        from python_core.utils.logger import get_logger
        return get_logger(__name__)
    except ImportError:
        try:
            from utils.logger import get_logger
            return get_logger(__name__)
        except ImportError:
            print("WARNING: Failed to setup logging", file=sys.stderr)
            return None

def create_json_response(status, message, data=None):
    """创建JSON响应"""
    response = {
        "status": status,
        "msg": message,
        "data": data
    }
    return json.dumps(response, ensure_ascii=False, indent=2)

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

        # 尝试多种导入方式
        module = None
        import_errors = []

        # 方式1: 完整路径导入
        try:
            module = __import__(f"python_core.{module_path}", fromlist=[function_name])
        except ImportError as e:
            import_errors.append(f"python_core.{module_path}: {e}")

        # 方式2: 相对路径导入
        if module is None:
            try:
                module = __import__(module_path, fromlist=[function_name])
            except ImportError as e:
                import_errors.append(f"{module_path}: {e}")

        # 方式3: 使用模拟服务
        if module is None:
            try:
                from mock_services import get_mock_service
                mock_service = get_mock_service(module_path)
                if mock_service and hasattr(mock_service, function_name):
                    print(f"Using mock service for {module_path}.{function_name}")
                    return getattr(mock_service, function_name)
            except ImportError:
                pass

        # 方式4: 直接导入（用于测试）
        if module is None and module_name == 'test':
            return create_test_function(function_name)

        if module is None:
            raise ImportError(f"Failed to import module '{module_path}'. Tried: {'; '.join(import_errors)}")

        # 获取函数
        if hasattr(module, function_name):
            return getattr(module, function_name)
        else:
            raise AttributeError(f"Function '{function_name}' not found in module '{module_path}'")

    except Exception as e:
        raise Exception(f"Failed to load function '{function_name}' from '{module_path}': {e}")

def create_test_function(function_name):
    """创建测试函数"""
    def test_function(**kwargs):
        return {
            "function": function_name,
            "params": kwargs,
            "message": f"Test function '{function_name}' executed successfully",
            "timestamp": str(Path(__file__).stat().st_mtime)
        }
    return test_function

def execute_action(module_name, action, params=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)

        # 执行函数
        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 main():
    """主函数"""
    try:
        # 解析参数
        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('--verbose', '-v', action='store_true',
                           help='Enable verbose logging')

        parser.add_argument('--version', action='version', version='MixVideo V2 Python Core 2.0.0')

        args = parser.parse_args()

        # 设置日志级别
        if args.verbose:
            os.environ['LOG_LEVEL'] = 'DEBUG'

        # 解析参数
        params = {}
        if args.params:
            try:
                params = json.loads(args.params)
            except json.JSONDecodeError as e:
                error_response = create_json_response(False, f"Invalid JSON parameters: {e}")
                print(error_response)
                return 1

        # 执行动作
        result = execute_action(args.module, args.action, params)

        # 发送成功响应
        response = create_json_response(True, "操作完成", result)
        print(response)
        return 0

    except KeyboardInterrupt:
        error_response = create_json_response(False, "Operation cancelled by user")
        print(error_response)
        return 130
    except Exception as e:
        error_response = create_json_response(False, str(e))
        print(error_response)
        return 1

if __name__ == "__main__":
    sys.exit(main())
