# main.py
import sys
import os
import io
import json
import traceback
import re
import requests
import numpy as np
import librosa
from config import get_base_dir, get_project_path, get_lib_path, get_data_cache_dir, get_config
from core import subtitle_utils
import logging
from datetime import datetime
from core.logger import get_logger

# 强制设置 UTF-8 编码，防止与 Electron 通讯时中文乱码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 优先从 config 获取路径配置
BASE_DIR = get_base_dir()
PROJECT_PATH = get_project_path()
LIB_PATH = get_lib_path()
logger = get_logger('bgxiong_main')
logger.info("====== 插件启动 ======")


if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)
if PROJECT_PATH not in sys.path:
    sys.path.insert(0, PROJECT_PATH)
if os.path.exists(LIB_PATH) and LIB_PATH not in sys.path:
    sys.path.insert(0, LIB_PATH)
logger.debug("PROJECT_PATH: " + PROJECT_PATH)
logger.debug("LIB_PATH: " + LIB_PATH)

if sys.platform.startswith("win"):
    RESOLVE_SCRIPT_API = os.environ.get('PROGRAMDATA') + '\\Blackmagic Design\\DaVinci Resolve\\Support\\Developer\\Scripting'
    RESOLVE_MODULES_PATH = RESOLVE_SCRIPT_API + '\\Modules'
    RESOLVE_PYTHON_PATH = r"C:\Program Files\Blackmagic Design\DaVinci Resolve\fusionscript\python"
elif sys.platform.startswith("darwin"):
    RESOLVE_SCRIPT_API = '/Library/Application Support/Blackmagic Design/DaVinci Resolve/Developer/Scripting'
    RESOLVE_MODULES_PATH = RESOLVE_SCRIPT_API + '/Modules'
    RESOLVE_PYTHON_PATH = '/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts/fusionscript/python'
else:
    RESOLVE_MODULES_PATH = None
    RESOLVE_PYTHON_PATH = None

# 将 Resolve 模块路径加入 sys.path
for p in [RESOLVE_MODULES_PATH, RESOLVE_PYTHON_PATH]:
    if p and p not in sys.path:
        sys.path.insert(0, p)

# ============================================
# 导入核心模块
# ============================================
from core.resolve_api import get_resolve

# ==========================================
# 4. 初始化配置
# ==========================================
config = get_config()
BASE_URL = config.get("api_base_url", "http://www.bgxiong.com/client/v1/")
DATA_CACHE_DIR = get_data_cache_dir()
FIXED_CACHE_FILENAME = "audio_scan.json"
FIXED_CACHE_FILEPATH = os.path.join(DATA_CACHE_DIR, FIXED_CACHE_FILENAME)

from core.audio_analysis import (
    get_audio_data_handler,
    analyze_dir_handler,
    extract_waveform_data
)
from core.media_import import import_sfx
from auth.auth_handlers import (
    login_handler,
    reg_handler,
    activate_handler
)
from network.downloader import (
    download_remote_file_handler,
    download_json_handler
)
from network.api_client import (
    fetch_json_handler,
    fetch_html_handler,
    sfx_list_handler,
    hot_tags_handler
)

# ==========================================
# 5. 命令路由配置
# ==========================================
COMMAND_ROUTER = {
    "hot_tags": {
        "handler": hot_tags_handler,
        "required_args": 0,
        "description": "獲取热门标签"
    },
    "download_json": {
        "handler": lambda payload: download_json_handler(payload, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "返回远程 JSON 数据"
    },
    "download_remote_file": {
        "handler": lambda payload: download_remote_file_handler(payload, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "下載遠程文件到本地緩存"
    },
    "sfx_list": {
        "handler": lambda payload: sfx_list_handler(payload, BASE_URL),
        "required_args": 1,
        "description": "獲取云端音效列表"
    },
    "get_audio_data": {
        "handler": lambda: get_audio_data_handler(FIXED_CACHE_FILEPATH),
        "required_args": 0,
        "description": "獲取本地緩存的分析數據"
    },
    "analyze_dir": {
        "handler": lambda path: analyze_dir_handler(path, FIXED_CACHE_FILEPATH, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "分析本地目錄文件"
    },
    "login": {
        "handler": lambda payload: login_handler(payload, BASE_URL, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "用戶登錄"
    },
    "reg": {
        "handler": lambda payload: reg_handler(payload, BASE_URL, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "用戶註冊"
    },
    "activate": {
        "handler": lambda payload: activate_handler(payload, BASE_URL, DATA_CACHE_DIR),
        "required_args": 1,
        "description": "用戶激活"
    },
    "fetch_html": {
        "handler": lambda payload: fetch_html_handler(payload),
        "required_args": 1,
        "description": "获取远程 HTML 内容并返回字符串"
    },
    "fetch_json": {
        "handler": lambda payload: fetch_json_handler(payload, BASE_URL),
        "required_args": 1,
        "description": "获取远程 JSON 内容并返回字符串"
    },
    "import_sfx": {
        "handler": lambda payload: _import_sfx_handler(payload),
        "required_args": 1,
        "description": "导入音效到媒体池"
    },

    # ⭐ 字幕命令 - 改为字典格式（与其他命令一致）
    "get_subtitle_list": {
        "handler": subtitle_utils.get_subtitle_list,
        "required_args": 0,  # 不需要额外参数
        "description": "获取当前时间线字幕列表"
    },
    "create_subtitles": {
        "handler": subtitle_utils.create_subtitles,
        "required_args": 1,  # 需要 1 个参数：字幕 JSON 字符串
        "description": "创建字幕"
    },
    "export_current_timeline_subtitles": {
        "handler": subtitle_utils.export_current_timeline_subtitles,
        "required_args": 0,  # 不需要额外参数
        "description": "导出当前时间线字幕"
    },
    "save_subtitle_changes": {
        "handler": subtitle_utils.save_subtitle_changes,
        "required_args": 1,  # 需要 1 个参数：修改的字幕 JSON 字符串
        "description": "保存字幕修改到时间线"
    },
    "get_timeline_info": {
        "handler": subtitle_utils.get_timeline_info,
        "required_args": 0,  # 不需要额外参数
        "description": "获取当前时间线信息（名称、帧率、分辨率等） "
    },
    "import_subtitles_from_srt": {
        "handler": subtitle_utils.import_subtitles_from_srt,
        "required_args": 1,
        "description": ""
    },
    "save_subtitle_changes": {
        "handler": subtitle_utils.save_subtitle_changes,
        "required_args": 1,
        "descprtion": ""
    },
    "subtitle_save_replace_rules": {
        "handler": subtitle_utils.subtitle_save_replace_rules,
        "required_args": 1,
        "descprtion": ""
    },
    "subtitle_load_replace_rules": {
        "handler": subtitle_utils.subtitle_load_replace_rules,
        "required_args": 0,
        "descprtion": ""
    },        
}

def _import_sfx_handler(payload_str):
    """处理音效导入的包装函数"""
    payload = json.loads(payload_str)
    file_path = payload.get("file_path")
    display_name = payload.get("display_name")
    
    if not file_path or not display_name:
        raise ValueError("Missing required fields: file_path or display_name")
    
    return import_sfx(get_resolve(), file_path, display_name)

def main():
    """程序主入口"""
    try:
        # 驗證參數數量
        if len(sys.argv) < 3:
            raise ValueError("缺少命令參數。可用命令: " + ", ".join(COMMAND_ROUTER.keys()))
        
        # 核心修正位置：
        data_dir = sys.argv[1]  # 獲取 Electron 傳過來的固定路徑
        command = sys.argv[2]   # 命令現在是在索引 2
        
        # 檢查命令是否存在
        if command not in COMMAND_ROUTER:
            raise ValueError(f"未知命令: '{command}'。可用命令: {', '.join(COMMAND_ROUTER.keys())}")
        
        cmd_config = COMMAND_ROUTER[command]  # 獲取命令配置
        handler = cmd_config["handler"]  # 處理函數
        required_args = cmd_config["required_args"]  # 需要的參數數量

        args = sys.argv[3:3 + required_args]
        
        # 執行處理函數
        result = handler(*args) if args else handler()

        # 標準化成功響應
        print(json.dumps({
            "status": "success",
            "success": True,
            "command": command,
            "data": result
        }))
    except Exception as e:
        # 結構化錯誤響應
        error_data = {
            "status": "error",
            "success": False,
            "command": sys.argv[2] if len(sys.argv) > 2 else "unknown",
            "message": str(e),
            "args_received": sys.argv[1:],
            # 限制堆棧跟蹤長度 (避免敏感信息洩露)
            "traceback": traceback.format_exc().splitlines()[-5:] 
        }
        
        # 輸出到 stderr (Electron 可捕獲)
        print(json.dumps(error_data), file=sys.stderr)
        sys.exit(1)  # 非0退出碼表示失敗

if __name__ == "__main__":
    main()