import os
import json

from .utils import get_state
from .curate_music import run_music_curation
from .curate_internet import run_internet_curation
from .module_subtitles import extract_subtitles_from_video

def interactive_curation(job_dir, auto_mode=False):
    """
    Performs curation of a video job.
    
    Args:
        job_dir: Path to the job directory
        auto_mode: If True, automatically accepts AI suggestions without user confirmation
    """
    state = get_state(job_dir)

    # 0. Untertitel extrahieren (falls im MKV eingebettet)
    video_path = None
    if os.path.exists(job_dir):
        for f in os.listdir(job_dir):
            if f.startswith("original.") and f.endswith((".mkv", ".webm", ".mp4")):
                video_path = os.path.join(job_dir, f)
                break
    if video_path:
        extract_subtitles_from_video(job_dir, video_path)

    json_path = os.path.join(job_dir, "original.info.json")
    
    meta = {}
    if os.path.exists(json_path):
        with open(json_path, "r") as f: meta = json.load(f)
        
    orig_title = meta.get("title", os.path.basename(job_dir))
    orig_desc = meta.get("description", "")
    channel = meta.get("channel") or meta.get("uploader") or "Unknown"
    
    # Entscheidung: Musik oder Internet?
    target_name = state.get("target", "Allgemein")
    is_music_video = (target_name == "Musikvideos" or target_name == "Musik")

    mode_label = "Auto-Kuratierung" if auto_mode else "Kuratierung"
    print(f"\n--- 🎨 {mode_label}: {orig_title[:50]}... ---")

    if is_music_video:
        # WORKFLOW A: MUSIK
        run_music_curation(job_dir, meta, orig_title, channel, auto_mode=auto_mode)
    else:
        # WORKFLOW B: INTERNET
        run_internet_curation(job_dir, meta, orig_title, orig_desc, channel, auto_mode=auto_mode)