import os
from .utils import save_state, get_state
from .module_mosaic import handle_poster_selection
from .module_language import detect_language_from_text
from .module_chapters import generate_chapters
from .claude_helper import analyze_internet_video
from .config import CONFIG, get_available_targets

def format_seconds(seconds):
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return "{:02d}:{:02d}:{:02d}".format(int(h), int(m), int(s))

def _is_youtube_source(meta):
    """Prüft ob das Video von YouTube stammt anhand des extractor-Feldes."""
    extractor = (meta.get("extractor_key") or meta.get("extractor") or "").lower()
    return extractor in ("youtube", "youtube:tab", "youtube:playlist")

def run_internet_curation(job_dir, meta, orig_title, orig_desc, channel, auto_mode=False):
    """Workflow B: Internetvideos
    
    Args:
        job_dir: Path to the job directory
        meta: Video metadata dictionary
        orig_title: Original video title
        orig_desc: Original video description
        channel: Channel/uploader name
        auto_mode: If True, automatically accepts AI suggestions without user confirmation
    """
    
    is_youtube = _is_youtube_source(meta)
    
    # 1. SPRACHERKENNUNG
    print(f"   🤖 [1/3] Erkenne Sprache aus Titel/Beschreibung...")
    lang_code_3, lang_name = detect_language_from_text(orig_title, orig_desc, channel)
    
    if len(lang_code_3) != 3: lang_code_3 = "und"
    lang_code_2 = lang_code_3[:2] 
    print(f"      ✅ Erkannt: {lang_name} (ISO: {lang_code_3})")

    # 2. VTT SUCHEN
    vtt_candidates = [f for f in os.listdir(job_dir) if f.endswith(".vtt")]
    vtt_path = None
    
    # Verbesserte Suche (wie in Build-Phase)
    # Sortieren: 1. Ohne 'orig', 2. Länge (kürzer ist besser)
    vtt_candidates.sort(key=lambda x: (1 if "orig" in x else 0, len(x)))

    candidates_lang = []
    search_terms = [f".{lang_code_2}.", f"-{lang_code_2}.", f"_{lang_code_2}.", f".{lang_code_2}-", f".{lang_code_3}."]
    if lang_code_2 == "de": search_terms.extend([".deu.", ".ger."])
    if lang_code_2 == "en": search_terms.extend([".eng."])
    
    for v in vtt_candidates:
        v_lower = v.lower()
        for term in search_terms:
            if term in v_lower:
                candidates_lang.append(os.path.join(job_dir, v))
                break
    
    if candidates_lang:
        vtt_path = candidates_lang[0]
    
    # Fallback: Suche nach 'orig'
    if not vtt_path:
        for f in vtt_candidates:
            if "orig" in f.lower(): vtt_path = os.path.join(job_dir, f); break
                
    # Fallback: Irgendeine
    if not vtt_path and vtt_candidates: 
        vtt_path = os.path.join(job_dir, vtt_candidates[0])

    if vtt_path: print(f"   📄 Nutze Transkript: {os.path.basename(vtt_path)}")
    else: print(f"   ℹ️  Kein Transkript gefunden.")

    # Video-Datei finden (für Upload bei fehlenden Untertiteln)
    video_path = None
    for f in os.listdir(job_dir):
        if f.lower().startswith("original.") and f.lower().endswith((".mp4", ".mkv", ".webm")):
            video_path = os.path.join(job_dir, f)
            break
            
    # Video-URL ermitteln (nur für YouTube-Quellen)
    video_url = None
    if is_youtube:
        video_url = meta.get("webpage_url")
        if not video_url and meta.get("id"):
            video_url = f"https://www.youtube.com/watch?v={meta.get('id')}"

    # 3. METADATEN ANALYSE
    ai_data = None
    if is_youtube:
        # YouTube-Quelle: K.I.-Analyse mit Claude
        tags = meta.get("tags", [])
        ai_data = analyze_internet_video(orig_title, channel, orig_desc, vtt_path, known_lang_name=lang_name, tags=tags, video_path=video_path, video_url=video_url)
        
        # In auto mode, we require AI data to proceed
        if auto_mode and not ai_data:
            raise Exception("K.I.-Analyse fehlgeschlagen. Auto-Kuratierung kann nicht fortgesetzt werden.")
    else:
        # Nicht-YouTube-Quelle: Manueller Modus
        extractor = meta.get("extractor_key") or meta.get("extractor") or "Unbekannt"
        print(f"   ℹ️  Quelle: {extractor} (kein YouTube)")
        print(f"   📝 Manueller Modus für Titel und Beschreibungen.")
    
    final_title = orig_title
    final_genre = "Internet"
    final_tags = ""
    final_short_desc = orig_desc[:250] + "..." if orig_desc else ""
    final_long_desc = orig_desc

    if not is_youtube and not ai_data:
        # Manueller Modus für Nicht-YouTube-Quellen
        print(f"\n--- 📝 TITEL ---")
        print(f"   Original: {orig_title}")
        new_title = input("   Neuer Titel (ENTER = Original übernehmen): ").strip()
        if new_title:
            final_title = new_title

        print(f"\n--- 📖 KURZBESCHREIBUNG (Teaser) ---")
        if final_short_desc:
            print(f"   Vorhanden: {final_short_desc}")
            new_short = input("   Neue Kurzbeschreibung (ENTER = übernehmen): ").strip()
            if new_short:
                final_short_desc = new_short
        else:
            new_short = input("   Kurzbeschreibung (ENTER = leer): ").strip()
            final_short_desc = new_short

        print(f"\n--- 📜 LANGBESCHREIBUNG (Volltext) ---")
        if final_long_desc:
            print(f"   Vorhanden: {final_long_desc[:200]}{'...' if len(final_long_desc) > 200 else ''}")
            new_long = input("   Neue Langbeschreibung (ENTER = übernehmen): ").strip()
            if new_long:
                final_long_desc = new_long
        else:
            new_long = input("   Langbeschreibung (ENTER = leer): ").strip()
            final_long_desc = new_long

    elif ai_data:
        print(f"   🌍 Genre: {ai_data.get('genre')}")
        print(f"   🏷️  Tags:  {ai_data.get('tags')}")
        
        # Handle "Auto" target - automatically classify when target is "Auto"
        current_target = get_state(job_dir).get("target", "")
        if current_target == "Auto" and CONFIG.get("classification_enabled", False):
            try:
                from .module_classification_rules import suggest_target_for_video
                
                # Prepare metadata for classification
                video_metadata = {
                    "genre": ai_data.get("genre", ""),
                    "grouping": ai_data.get("tags", ""),
                    "artist": channel
                }
                
                # Get suggestions
                suggestions = suggest_target_for_video(video_metadata, top_n=1)
                
                if suggestions:
                    suggested_target = suggestions[0][0]  # Get the top suggestion
                    confidence = suggestions[0][1]
                    reason = suggestions[0][2]
                    confidence_pct = int(confidence * 100)
                    
                    print(f"\n   🤖 Auto-Klassifikation:")
                    print(f"      Vorgeschlagenes Ziel: {suggested_target} ({confidence_pct}%)")
                    print(f"      Grund: {reason}")
                    
                    # In auto_mode, apply automatically; otherwise ask for confirmation
                    if auto_mode:
                        # Update state with suggested target
                        current_state = get_state(job_dir)
                        current_state["target"] = suggested_target
                        save_state(job_dir, current_state)
                        print(f"      ✅ Ziel automatisch gesetzt: {suggested_target}")
                    else:
                        # Manual confirmation
                        apply_suggestion = input(f"\n   Vorschlag übernehmen? [Y/n]: ").strip().lower()
                        if apply_suggestion in ['', 'y', 'j', 'ja', 'yes']:
                            current_state = get_state(job_dir)
                            current_state["target"] = suggested_target
                            save_state(job_dir, current_state)
                            print(f"   ✅ Ziel geändert zu: {suggested_target}")
                        else:
                            # Let user choose manually
                            print("\n   Verfügbare Zielverzeichnisse:")
                            targets = get_available_targets()
                            
                            for i, t in enumerate(targets, 1):
                                print(f"      {i}. {t}")
                            
                            target_sel = input(f"   Auswahl (1-{len(targets)}): ").strip()
                            if target_sel.isdigit() and 1 <= int(target_sel) <= len(targets):
                                new_target = targets[int(target_sel) - 1]
                                current_state = get_state(job_dir)
                                current_state["target"] = new_target
                                save_state(job_dir, current_state)
                                print(f"   ✅ Ziel geändert zu: {new_target}")
                else:
                    # No suggestions available - fall back to first target
                    print(f"\n   ⚠️  Keine Klassifikations-Vorschläge verfügbar")
                    targets = get_available_targets()
                    if targets:
                        fallback_target = targets[0]
                        current_state = get_state(job_dir)
                        current_state["target"] = fallback_target
                        save_state(job_dir, current_state)
                        print(f"   ℹ️  Fallback zu: {fallback_target}")
            
            except Exception as e:
                # Handle classification errors - fall back to first target
                print(f"   ⚠️  Auto-Klassifikation fehlgeschlagen: {e}")
                if CONFIG.get('debug_mode', False):
                    import traceback
                    traceback.print_exc()
                
                targets = get_available_targets()
                if targets:
                    fallback_target = targets[0]
                    current_state = get_state(job_dir)
                    current_state["target"] = fallback_target
                    save_state(job_dir, current_state)
                    print(f"   ℹ️  Fallback zu: {fallback_target}")
        
        # Show classification suggestions if enabled (for non-Auto targets)
        elif CONFIG.get("classification_enabled", False) and not auto_mode and current_target != "Auto":
            try:
                from .module_classification_rules import suggest_target_for_video
                
                # Prepare metadata for classification
                video_metadata = {
                    "genre": ai_data.get("genre", ""),
                    "grouping": ai_data.get("tags", ""),
                    "artist": channel
                }
                
                # Get suggestions
                suggestions = suggest_target_for_video(video_metadata, top_n=3)
                
                if suggestions:
                    print("\n   🧠 Klassifikations-Vorschläge für Zielverzeichnis:")
                    current_target = get_state(job_dir).get("target", "Unbekannt")
                    print(f"      Aktuell: {current_target}")
                    
                    for i, (target, confidence, reason) in enumerate(suggestions, 1):
                        confidence_pct = int(confidence * 100)
                        print(f"      {i}. {target} ({confidence_pct}%) - {reason}")
                    
                    # Ask user if they want to change target
                    change_target = input("\n   Zielverzeichnis ändern? [y/N]: ").strip().lower()
                    
                    if change_target in ['y', 'j', 'ja', 'yes']:
                        print("\n   Verfügbare Zielverzeichnisse:")
                        targets = get_available_targets()
                        
                        for i, t in enumerate(targets, 1):
                            print(f"      {i}. {t}")
                        
                        target_sel = input(f"   Auswahl (1-{len(targets)}): ").strip()
                        if target_sel.isdigit() and 1 <= int(target_sel) <= len(targets):
                            new_target = targets[int(target_sel) - 1]
                            # Update state with new target
                            current_state = get_state(job_dir)
                            current_state["target"] = new_target
                            save_state(job_dir, current_state)
                            print(f"   ✅ Zielverzeichnis geändert zu: {new_target}")
            
            except Exception as e:
                # Silently ignore classification errors - they're not critical
                if CONFIG.get('debug_mode', False):
                    print(f"   ⚠️  Klassifikations-Fehler: {e}")
        
        titles = ai_data.get("titles", [orig_title])
        
        if auto_mode:
            # Auto mode: automatically select first title
            # Safety check: ensure titles list is not empty
            if titles:
                final_title = titles[0]
            else:
                final_title = orig_title
                print("   ⚠️  Keine Titel-Vorschläge vorhanden, nutze Original-Titel")
            print(f"\n--- 📝 TITEL (Auto) ---")
            print(f"   ✅ Gewählt: {final_title}")
        else:
            # Manual mode: let user choose
            print("\n--- 📝 TITEL ---")
            for i, t in enumerate(titles, 1): print(f"{i}. {t}")
            print("\n   [ENTER] übernimmt: 1")
            sel = input("   Wähle (1-4): ").strip()
            final_title = titles[int(sel)-1] if sel.isdigit() and 1 <= int(sel) <= len(titles) else titles[0]
            
        final_genre = ai_data.get("genre", "Internet")
        final_tags = ai_data.get("tags", "")
        final_short_desc = ai_data.get("description_short") or ""
        final_long_desc = ai_data.get("description_long") or ""

    # REVIEW (nur für YouTube-Quellen / AI-gestützte Kuratierung)
    if is_youtube or ai_data:
        if auto_mode:
            # Auto mode: automatically accept descriptions
            print("\n--- 📖 KURZBESCHREIBUNG (Teaser, Auto) ---")
            print(f"{final_short_desc}")
            print("\n--- 📜 LANGBESCHREIBUNG (Volltext, Auto) ---")
            print(f"{final_long_desc}")
            print("   ✅ Beschreibungen automatisch übernommen")
        else:
            # Manual mode: review and confirm
            print("\n--- 📖 KURZBESCHREIBUNG (Teaser) ---")
            print(f"{final_short_desc}")
            print("\n--- 📜 LANGBESCHREIBUNG (Volltext) ---")
            print(f"{final_long_desc}")
            print("-" * 30)
            print("   Übernehmen? [ENTER] Ja | [n] Nein")
            if input("   Auswahl: ").strip().lower() == 'n':
                new_d = input("   Neue Kurzbeschreibung: ").strip()
                if new_d: final_short_desc = new_d

    # 4. KAPITEL
    chapter_file = os.path.join(job_dir, "chapters.txt")
    if os.path.exists(chapter_file): os.remove(chapter_file)
    orig_chapters = meta.get("chapters", [])
    
    if orig_chapters:
        try:
            print(f"\n📑 Original-Kapitel übernommen:")
            with open(chapter_file, "w") as f:
                for i, chap in enumerate(orig_chapters):
                    timestamp = format_seconds(chap.get('start_time',0))
                    title = chap.get('title','Chap')
                    
                    # Wenn erstes Kapitel leer oder generisch ist -> "Intro"
                    if i == 0 and (not title or title == "Chap" or title.startswith("<Untitled")):
                        title = "Intro"
                        
                    f.write(f"{timestamp} - {title}\n")
                    print(f"   {timestamp} - {title}")
        except: pass
    elif vtt_path:
        print(f"   🤖 Generiere Kapitel aus Transkript...")
        chapters = generate_chapters(vtt_path, lang_name)
        if chapters:
            print(f"   ✅ AI-Kapitel erstellt:")
            with open(chapter_file, "w") as f:
                for i, chap in enumerate(chapters):
                    timestamp = chap.get('start')
                    title = chap.get('title', 'Kapitel')
                    
                    # Auch hier: Erstes Kapitel ohne Namen -> Intro
                    if i == 0 and (not title or title == "Kapitel" or title.startswith("<Untitled")):
                        title = "Intro"
                        
                    f.write(f"{timestamp} - {title}\n")
                    print(f"      {timestamp} - {title}")
        else:
            print(f"   ⚠️  Keine Kapitel generiert (API oder Transkript leer).")

    handle_poster_selection(job_dir, meta, auto_mode=auto_mode, curated_title=final_title)

    print(f"   🗣️  Audio-Sprache: {lang_code_3}")

    save_state(job_dir, {
        "curated_title": final_title,
        "curated_genre": final_genre,
        "curated_tags": final_tags,
        "curated_description": final_short_desc,
        "curated_long_description": final_long_desc, 
        "language_code": lang_code_3,
        "is_curated": True
    })
    
    print(f"\n✅ Final:\nTitel: {final_title}\nGenre: {final_genre}\nTags:  {final_tags}\n")