import os
import re
import json
from .config import CONFIG
from .utils import run_shell

def extract_subtitles_from_video(job_dir, video_path):
    """Extrahiert Untertitel aus dem Video, falls keine externen VTTs da sind."""
    if not video_path or not os.path.exists(video_path): return

    # Check ob schon VTTs da sind
    existing = [f for f in os.listdir(job_dir) if f.endswith(".vtt")]
    if existing:
        return # Schon da
        
    print(f"   🔍 Suche eingebettete Untertitel in {os.path.basename(video_path)}...")
    
    # ffprobe streams
    cmd = f"{CONFIG['ffprobe']} -v error -print_format json -show_streams '{video_path}'"
    try:
        output = run_shell(cmd, return_output=True)
        data = json.loads(output)
    except Exception as e:
        print(f"   ⚠️  Konnte Streams nicht lesen: {e}")
        return

    streams = data.get("streams", [])
    sub_streams = [s for s in streams if s.get("codec_type") == "subtitle"]
    
    if not sub_streams:
        print("   ℹ️  Keine Untertitel-Spuren gefunden.")
        return
        
    print(f"   found {len(sub_streams)} subtitle tracks.")
    
    for stream in sub_streams:
        idx = stream.get("index")
        tags = stream.get("tags", {})
        lang = tags.get("language", "und")
        title = tags.get("title", "")
        
        # Output filename
        # Format: original.lang.vtt
        out_name = f"original.{lang}.vtt"
        if title:
             # Sanitize title to avoid weird chars
             safe_title = re.sub(r'[^a-zA-Z0-9]', '', title)
             if safe_title: out_name = f"original.{lang}.{safe_title}.vtt"
             
        out_path = os.path.join(job_dir, out_name)
        
        print(f"   📥 Extrahiere Stream #{idx} ({lang}) -> {out_name}")
        # ffmpeg extract
        # Use -loglevel fatal to suppress non-fatal Opus packet header errors
        extract_cmd = (
            f"{CONFIG['ffmpeg']} -i '{video_path}' "
            f"-map 0:{idx} -f webvtt -y '{out_path}' "
            f"-hide_banner -loglevel fatal"
        )
        try:
            run_shell(extract_cmd)
        except:
            print(f"   ⚠️  Fehler beim Extrahieren von Stream {idx}")

def parse_vtt_text(vtt_path, with_timestamps=False):
    """Hilfsfunktion: Liest VTT ein."""
    if not vtt_path or not os.path.exists(vtt_path): return ""
    text_content = ""
    try:
        with open(vtt_path, "r", encoding="utf-8") as f:
            lines = f.readlines()
        seen_lines = set()
        # Flexibler Regex: Unterstützt HH:MM:SS und MM:SS
        time_pattern = re.compile(r"((?:\d{1,2}:)?\d{2}:\d{2})")
        current_time = None
        buffer = []
        for line in lines:
            line = line.strip()
            # Ignoriere Header, Indizes oder leere Zeilen
            if "WEBVTT" in line or line.isdigit() or not line: continue
            
            if "-->" in line:
                if with_timestamps:
                    match = time_pattern.search(line)
                    if match:
                        time_str = match.group(1)
                        # Normalisiere auf HH:MM:SS wenn nötig
                        if len(time_str.split(":")) == 2:
                            time_str = "00:" + time_str
                        
                        if current_time and buffer:
                            text_content += f"[{current_time}] {' '.join(buffer)}\n"
                            buffer = []
                        current_time = time_str
                continue
            if with_timestamps:
                if line not in buffer: buffer.append(line)
            else:
                if line not in seen_lines:
                    text_content += line + " "
                    seen_lines.add(line)
        if with_timestamps and current_time and buffer:
            text_content += f"[{current_time}] {' '.join(buffer)}\n"
    except Exception as e: print(f"⚠️  Fehler beim Lesen des Transkripts: {e}")
    return text_content[:25000] if not with_timestamps else text_content[:60000]