import re
import os
import requests
import time
from typing import List, Dict, Tuple
import docx

class SubtitleProcessor:
    """字幕处理器：生成字幕、语义分段等"""
    
    def __init__(self):
        # 使用SiliconFlow API进行语义分段
        # CHATFIRE_API_BASE = "https://api.chatfire.cn/v1"
        # CHATFIRE_API_KEY = "sk-QwXT3QeorfDPerfxs2Q76i9yDoKvOOG90Q135BNKtYXB3yE2"
        self.api_key = os.environ.get('SILICONFLOW_API_KEY', 'sk-5w2FNpdHmV4xoi07RAe2lWiqXGgvRWCbmCk9o8T39hZBhJIc')
        self.base_url = os.environ.get('SILICONFLOW_BASE_URL', 'https://jeniya.cn/')
        # self.api_key = os.environ.get('SILICONFLOW_API_KEY', 'sk-QwXT3QeorfDPerfxs2Q76i9yDoKvOOG90Q135BNKtYXB3yE2')
        # self.base_url = os.environ.get('SILICONFLOW_BASE_URL', 'https://api.chatfire.cn/v1')
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        
        # # 配置代理（如果环境变量中有设置）
        # if os.environ.get('HTTP_PROXY'):
        #     os.environ["http_proxy"] = os.environ.get('HTTP_PROXY')
        # if os.environ.get('HTTPS_PROXY'):
        #     os.environ["https_proxy"] = os.environ.get('HTTPS_PROXY')
    
    def extract_time_coded_content_from_docx(self, file_path):
        """从Word文档中提取带时间戳的内容"""
        doc = docx.Document(file_path)
        full_text = '\n'.join([para.text for para in doc.paragraphs])
        lines = full_text.split('\n')
        
        time_coded_content = {}
        current_time_code = None
        current_content = []
        
        for line in lines:
            if line.startswith('发言人') and ' ' in line:
                if current_time_code:
                    time_coded_content[current_time_code] = ' '.join(current_content).strip()
                    current_content = []
                
                time_code = line.split()[1]
                current_time_code = time_code
            elif current_time_code:
                current_content.append(line)
        
        if current_time_code:
            time_coded_content[current_time_code] = ' '.join(current_content).strip()
        
        # 格式化输出
        formatted_output = []
        time_codes = sorted(list(time_coded_content.keys()))
        for i in range(len(time_codes)-1):
            start_time = time_codes[i]
            end_time = time_codes[i+1]
            content = time_coded_content[start_time]
            formatted_output.append({
                'timestamp': f"{start_time}-{end_time}",
                'content': content
            })
        
        return formatted_output
    
    def semantic_integration_with_llm(self, subtitle_text, max_retries=3):
        """使用LLM进行语义分段（参考SemanticSegmentation.py的实现）"""
        for attempt in range(max_retries):
            try:
                print(f"🔄 第 {attempt + 1}/{max_retries} 次尝试调用语义分段API...")
                print(f"   📡 API端点: {self.base_url}")
                print(f"   📝 输入文本长度: {len(subtitle_text)} 字符")
                
                # 参考SemanticSegmentation.py的prompt设计 - 简洁明了
                prompt = f"""现在需要你将下面的音频段落按照语义重新分段，输出格式为"时间戳":"内容"，内容不需要你总结，你只负责按照新的时间戳合并原文内容：

{subtitle_text}"""
                
                # 使用 https://jeniya.cn/ API
                data = {
                    "model": "gpt-5-mini",  # 使用更可靠的模型
                    "messages": [
                        {
                            "role": "user",
                            "content": prompt
                        }
                    ],
                    "temperature": 0.3  # 降低随机性

                }
                
                print(f"   🚀 发送API请求...")
                
                # 构建完整的API URL
                api_url = f"{self.base_url.rstrip('/')}/v1/chat/completions"
                print(f"   🌐 完整URL: {api_url}")
                
                response = requests.post(
                    api_url,
                    headers=self.headers,
                    json=data,
                    timeout=300  # 增加超时时间
                )
                
                print(f"   📥 收到响应，状态码: {response.status_code}")
                
                if response.status_code == 200:
                    result = response.json()
                    
                    # 检查响应格式
                    if 'choices' in result and len(result['choices']) > 0:
                        content = result['choices'][0]['message']['content']
                        print(f"   ✅ API调用成功！")
                        print(f"   📊 返回内容长度: {len(content)} 字符")
                        print(f"   📄 内容预览: {content[:200]}...")
                        
                        return content.strip()
                    else:
                        print(f"   ⚠️  响应格式异常: {result}")
                        raise Exception("API响应格式不正确")
                else:
                    print(f"   ❌ API调用失败，状态码: {response.status_code}")
                    print(f"   📄 响应内容: {response.text[:500]}")
                    
                    if attempt < max_retries - 1:
                        wait_time = (2 ** attempt)  # 指数退避：1s, 2s, 4s
                        print(f"   ⏳ 等待 {wait_time} 秒后重试...")
                        time.sleep(wait_time)
                    continue
                    
            except requests.exceptions.Timeout:
                print(f"   ⏱️  第 {attempt + 1} 次尝试超时")
                if attempt < max_retries - 1:
                    wait_time = (2 ** attempt)
                    print(f"   ⏳ 等待 {wait_time} 秒后重试...")
                    time.sleep(wait_time)
                else:
                    print(f"   ❌ 所有重试均超时")
                    return None
                    
            except requests.exceptions.RequestException as e:
                print(f"   ❌ 网络请求错误: {str(e)}")
                if attempt < max_retries - 1:
                    wait_time = (2 ** attempt)
                    print(f"   ⏳ 等待 {wait_time} 秒后重试...")
                    time.sleep(wait_time)
                else:
                    print(f"   ❌ 所有重试均失败")
                    return None
                    
            except Exception as e:
                print(f"   ❌ 未知错误: {type(e).__name__} - {str(e)}")
                import traceback
                traceback.print_exc()
                if attempt < max_retries - 1:
                    wait_time = (2 ** attempt)
                    print(f"   ⏳ 等待 {wait_time} 秒后重试...")
                    time.sleep(wait_time)
                else:
                    print(f"   ❌ 所有重试均失败")
                    return None
        
        print(f"   ❌ 经过 {max_retries} 次尝试后仍然失败")
        return None
    
    def parse_timestamps(self, text_content):
        """解析时间戳文本（支持多种格式）"""
        timestamps = {}
        
        # 多种时间戳格式的正则表达式模式
        patterns = [
            # 格式1: "00:01:30-00:02:45": "内容"
            r'"(\d{2}:\d{2}:\d{2})-(\d{2}:\d{2}:\d{2})":\s*"([^"]*)"',
            # 格式2: "01:30-02:45": "内容"
            r'"(\d{2}:\d{2})-(\d{2}:\d{2})":\s*"([^"]*)"',
            # 格式3: 无外引号
            r'(\d{2}:\d{2}:\d{2})-(\d{2}:\d{2}:\d{2}):\s*"([^"]*)"',
            # 格式4: MM:SS格式无外引号
            r'(\d{2}:\d{2})-(\d{2}:\d{2}):\s*"([^"]*)"',
        ]
        
        found_matches = []
        for pattern in patterns:
            matches = re.findall(pattern, text_content)
            if matches:
                for match in matches:
                    found_matches.append(match)
        
        if not found_matches:
            print("未找到匹配的时间戳格式")
            return timestamps
        
        print(f"找到 {len(found_matches)} 个时间戳分段")
        
        for idx, match in enumerate(found_matches):
            start_time, end_time, description = match
            
            # 标准化时间格式
            start_time = self._standardize_time_format(start_time)
            end_time = self._standardize_time_format(end_time)
            
            start_sec = self._time_to_seconds(start_time)
            end_sec = self._time_to_seconds(end_time)
            
            key = f"clip_{idx:03d}"
            timestamps[key] = {
                'start': start_sec,
                'end': end_sec,
                'content': description.strip(),
                'timestamp_str': f"{start_time}-{end_time}"
            }
        
        return timestamps
    
    def _standardize_time_format(self, time_str):
        """标准化时间格式"""
        # 如果是HH:MM:SS格式，直接返回
        if re.match(r'\d{2}:\d{2}:\d{2}', time_str):
            return time_str
        # 如果是MM:SS格式，添加小时部分
        if re.match(r'\d{2}:\d{2}', time_str):
            return f"00:{time_str}"
        return time_str
    
    def _time_to_seconds(self, time_str):
        """将时间字符串转换为秒数"""
        parts = list(map(int, time_str.split(':')))
        if len(parts) == 3:  # HH:MM:SS
            return parts[0] * 3600 + parts[1] * 60 + parts[2]
        elif len(parts) == 2:  # MM:SS
            return parts[0] * 60 + parts[1]
        return parts[0]  # SS
    
    def format_subtitle_for_display(self, timestamps):
        """格式化字幕用于前端显示"""
        subtitles = []
        
        for clip_name, data in timestamps.items():
            subtitles.append({
                'index': len(subtitles) + 1,
                'start_time': data['start'],
                'end_time': data['end'],
                'duration': data['end'] - data['start'],
                'content': data['content'],
                'timestamp': data['timestamp_str']
            })
        
        # 按开始时间排序
        subtitles.sort(key=lambda x: x['start_time'])
        
        return subtitles
    
    def process_subtitle_file(self, subtitle_file_path, process_id):
        """处理字幕文件"""
        try:
            with open(subtitle_file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 使用LLM进行语义分段
            semantic_content = self.semantic_integration_with_llm(content)
            
            # 保存语义分段结果 - 使用独立命名
            output_dir = os.path.join('processed', 'subtitles', process_id)
            os.makedirs(output_dir, exist_ok=True)
            
            # 使用独立命名：process_id + semantic
            semantic_filename = f'{process_id}_semantic_subtitles.txt'
            semantic_file = os.path.join(output_dir, semantic_filename)
            with open(semantic_file, 'w', encoding='utf-8') as f:
                f.write(semantic_content)
            
            # 解析时间戳
            timestamps = self.parse_timestamps(semantic_content)
            
            # 格式化用于显示
            subtitles = self.format_subtitle_for_display(timestamps)
            
            return {
                'subtitles': subtitles,
                'timestamps': timestamps,
                'semantic_file': f'/processed/subtitles/{process_id}/{semantic_filename}'
            }
            
        except Exception as e:
            print(f"字幕处理错误: {str(e)}")
            return None
    
    def create_subtitle_from_transcription(self, transcription_segments):
        """从转录文本创建字幕格式"""
        subtitle_text = ""
        
        for segment in transcription_segments:
            start = self._seconds_to_timestamp(segment['start_time'])
            end = self._seconds_to_timestamp(segment['end_time'])
            content = segment['text']
            subtitle_text += f'"{start}-{end}": "{content}"\n'
        
        return subtitle_text
    
    def _seconds_to_timestamp(self, seconds):
        """将秒数转换为时间戳格式"""
        hours = int(seconds // 3600)
        mins = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        return f"{hours:02d}:{mins:02d}:{secs:02d}"
    
    

