#!/usr/bin/env python3
"""
动态字幕模块 - 比格熊插件
提供 DaVinci Resolve Text+ 的完整属性控制和实时预览功能
"""
import sys
import os
import json
import threading
import time
from typing import Dict, Any, Optional

# 添加 DaVinci Resolve 脚本路径
def setup_resolve_path():
    """设置 DaVinci Resolve 脚本路径"""
    resolve_script_path = r"C:\ProgramData\Blackmagic Design\DaVinci Resolve\Support\Developer\Scripting\Modules"
    if resolve_script_path not in sys.path:
        sys.path.insert(0, resolve_script_path)
    
    # 处理 DLL 路径 (Windows)
    if sys.platform.startswith("win"):
        resolve_path = r"C:\Program Files\Blackmagic Design\DaVinci Resolve"
        if os.path.exists(resolve_path):
            if hasattr(os, 'add_dll_directory'):
                os.add_dll_directory(resolve_path)
            os.environ['PATH'] = resolve_path + os.pathsep + os.environ.get('PATH', '')

class DynamicSubtitleModule:
    """动态字幕主模块"""
    
    def __init__(self):
        self.resolve = None
        self.project = None
        self.timeline = None
        self.preview_thread = None
        self.preview_active = False
        self.current_settings = {
            'font': 'Arial',
            'size': 48,
            'color': {'r': 1.0, 'g': 1.0, 'b': 1.0, 'a': 1.0},
            'position': {'x': 0.5, 'y': 0.8},
            'alignment': 'center',
            'shadow': False,
            'outline': False
        }
        self.sample_text = "这里是天途影像，我是大熊！"
        
    def connect_resolve(self):
        """连接 DaVinci Resolve"""
        try:
            import DaVinciResolveScript as bmd
            self.resolve = bmd.scriptapp("Resolve")
            if not self.resolve:
                return False
            
            self.project = self.resolve.GetProjectManager().GetCurrentProject()
            if not self.project:
                return False
                
            self.timeline = self.project.GetCurrentTimeline()
            if not self.timeline:
                return False
                
            return True
        except Exception as e:
            print(f"连接 DaVinci Resolve 失败: {e}")
            return False
    
    def create_text_plus_node(self, text: str, settings: Dict[str, Any]) -> bool:
        """创建 Text+ 节点并应用设置"""
        try:
            if not self.connect_resolve():
                return False
            
            # 获取当前时间线项目
            current_item = self.timeline.GetCurrentVideoItem()
            if not current_item:
                # 创建新的媒体池项目
                media_pool = self.project.GetMediaPool()
                timeline_item = media_pool.AppendToTimeline([{
                    'mediaType': 'video',
                    'startFrame': 0,
                    'endFrame': 100
                }])[0]
            else:
                timeline_item = current_item
            
            # 创建 Fusion 复合
            fusion_comp = timeline_item.AddFusionComp()
            if not fusion_comp:
                return False
            
            # 创建 Text+ 节点
            text_plus = fusion_comp.AddTool("TextPlus")
            if not text_plus:
                return False
            
            # 应用文本内容
            text_plus.SetInput("StyledText", text)
            
            # 应用字体设置
            if 'font' in settings:
                text_plus.SetInput("Font", settings['font'])
            if 'size' in settings:
                text_plus.SetInput("Size", float(settings['size']))
            
            # 应用颜色设置
            if 'color' in settings:
                color = settings['color']
                text_plus.SetInput("Red", color['r'])
                text_plus.SetInput("Green", color['g'])
                text_plus.SetInput("Blue", color['b'])
                text_plus.SetInput("Alpha", color['a'])
            
            # 应用位置设置
            if 'position' in settings:
                pos = settings['position']
                text_plus.SetInput("XPosition", pos['x'])
                text_plus.SetInput("YPosition", pos['y'])
            
            # 应用对齐设置
            if 'alignment' in settings:
                alignment_map = {
                    'left': 0,
                    'center': 1,
                    'right': 2
                }
                text_plus.SetInput("Alignment", alignment_map.get(settings['alignment'], 1))
            
            return True
            
        except Exception as e:
            print(f"创建 Text+ 节点失败: {e}")
            return False
    
    def start_preview(self, callback=None):
        """启动实时预览"""
        if self.preview_active:
            return
        
        self.preview_active = True
        self.preview_thread = threading.Thread(target=self._preview_loop, args=(callback,))
        self.preview_thread.daemon = True
        self.preview_thread.start()
    
    def stop_preview(self):
        """停止实时预览"""
        self.preview_active = False
        if self.preview_thread:
            self.preview_thread.join()
            self.preview_thread = None
    
    def _preview_loop(self, callback=None):
        """预览循环"""
        last_settings = None
        while self.preview_active:
            if self.current_settings != last_settings:
                # 这里可以模拟预览效果（实际预览需要在 UI 层实现）
                if callback:
                    callback(self.sample_text, self.current_settings.copy())
                last_settings = self.current_settings.copy()
            time.sleep(0.1)
    
    def update_settings(self, new_settings: Dict[str, Any]):
        """更新设置"""
        self.current_settings.update(new_settings)
    
    def apply_to_timeline(self, subtitle_content: str):
        """将设置应用到时间线"""
        return self.create_text_plus_node(subtitle_content, self.current_settings)
    
    def save_to_cache(self, subtitle_content: str, cache_dir: str):
        """保存字幕到缓存目录"""
        try:
            cache_file = os.path.join(cache_dir, "dynamic_subtitle_cache.json")
            cache_data = {
                'subtitle_content': subtitle_content,
                'settings': self.current_settings,
                'timestamp': time.time()
            }
            with open(cache_file, 'w', encoding='utf-8') as f:
                json.dump(cache_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存缓存失败: {e}")
            return False

def main():
    """主函数 - 用于测试"""
    module = DynamicSubtitleModule()
    print("动态字幕模块已初始化")
    print(f"示例文本: {module.sample_text}")
    print(f"默认设置: {module.current_settings}")

if __name__ == "__main__":
    main()