import os
import json
from .config import CONFIG
from .utils import get_state, save_state
from .module_mosaic import handle_poster_selection
from .claude_helper import analyze_music_video

def load_music_state():
    """Lädt das Gedächtnis aus dem Haupt-Arbeitsverzeichnis."""
    path = os.path.join(CONFIG['work_dir'], ".last_music.json")
    if os.path.exists(path):
        try:
            with open(path, "r") as f: return json.load(f)
        except: pass
    # Return config default or fallback
    return {"sampler": CONFIG.get("default_music_album", "Unsorted")}

def save_music_state(sampler):
    path = os.path.join(CONFIG['work_dir'], ".last_music.json")
    with open(path, "w") as f:
        json.dump({"sampler": sampler}, f)

def run_music_curation(job_dir, meta, orig_title, channel, auto_mode=False):
    """Workflow A: Musikvideos
    
    Args:
        job_dir: Path to the job directory
        meta: Video metadata dictionary
        orig_title: Original video title
        channel: Channel/uploader name
        auto_mode: If True, automatically accepts AI suggestions without user confirmation
    """
    
    state = get_state(job_dir)
    duration = meta.get("duration", 0)
    
    # 1. SAMPLER
    last_state = load_music_state()
    playlist_title = meta.get("playlist_title") 
    
    # Use config default, then last state, then fallback
    config_default = CONFIG.get("default_music_album", "Unsorted")
    default_sampler = playlist_title if playlist_title else (last_state.get("sampler") or config_default)
    
    if auto_mode:
        # Auto mode: automatically use default sampler
        final_sampler = default_sampler
        print(f"   💿 Sampler (Album, Auto): '{final_sampler}'")
    else:
        # Manual mode: let user choose
        print(f"   💿 Sampler (Album):")
        print(f"      [ENTER] übernimmt: '{default_sampler}'")
        user_sampler = input(f"      Eingabe: ").strip()
        final_sampler = user_sampler if user_sampler else default_sampler

    # 2. CLAUDE ANALYSE
    print(f"   🧠 Frage Claude nach Künstler, Titel, Release-Jahr, Album & Tracknummer...")
    ai_music = analyze_music_video(orig_title, channel, meta.get("upload_date"), meta.get("description"))
    
    # In auto mode, we require AI data to proceed
    if auto_mode and not ai_music:
        raise Exception("K.I.-Analyse fehlgeschlagen. Auto-Kuratierung kann nicht fortgesetzt werden.")
    
    suggested_artist = ai_music.get("artist", channel) if ai_music else channel
    suggested_title = ai_music.get("title", orig_title) if ai_music else orig_title
    suggested_release_year = ai_music.get("release_year") if ai_music else None
    suggested_album = ai_music.get("album") if ai_music else None
    suggested_track_number = ai_music.get("track_number") if ai_music else None
    
    if auto_mode:
        # Auto mode: automatically use AI suggestions
        final_artist = suggested_artist
        final_title_song = suggested_title
        print(f"   🎤 Künstler (Artist, Auto): '{final_artist}'")
        print(f"   🎶 Titel (Song, Auto): '{final_title_song}'")
        if suggested_release_year:
            print(f"   📅 Release-Jahr (Auto): {suggested_release_year}")
        if suggested_album:
            print(f"   💿 Album (Auto): '{suggested_album}'")
        if suggested_track_number:
            print(f"   🔢 Tracknummer (Auto): {suggested_track_number}")
    else:
        # Manual mode: let user choose
        print(f"   🎤 Künstler (Artist):")
        print(f"      [ENTER] übernimmt: '{suggested_artist}'")
        user_artist = input(f"      Eingabe: ").strip()
        final_artist = user_artist if user_artist else suggested_artist
        
        print(f"   🎶 Titel (Song):")
        print(f"      [ENTER] übernimmt: '{suggested_title}'")
        user_title_song = input(f"      Eingabe: ").strip()
        final_title_song = user_title_song if user_title_song else suggested_title
        if suggested_release_year:
            print(f"   📅 Release-Jahr: {suggested_release_year}")
        if suggested_album:
            print(f"   💿 Album: '{suggested_album}'")
        if suggested_track_number:
            print(f"   🔢 Tracknummer: {suggested_track_number}")

    # Speichern (Gedächtnis)
    if not playlist_title:
        save_music_state(final_sampler)

    # Poster
    handle_poster_selection(job_dir, meta, auto_mode=auto_mode)

    # Job State
    save_state(job_dir, {
        "curated_artist": final_artist,
        "curated_title": final_title_song,
        "curated_album": final_sampler,
        "curated_genre": "Musikvideo",
        "curated_release_year": suggested_release_year,
        "curated_album_name": suggested_album,
        "curated_track_number": suggested_track_number,
        "is_curated": True,
        "target": state.get("target")
    })
    
    # Build summary message with optional parts
    optional_parts = [f"auf '{final_sampler}'"]
    if suggested_release_year:
        optional_parts.append(f"Jahr: {suggested_release_year}")
    if suggested_album:
        optional_parts.append(f"Album: '{suggested_album}'")
    if suggested_track_number:
        optional_parts.append(f"Track: {suggested_track_number}")
    
    summary = f"{final_artist} - {final_title_song}\n   ({', '.join(optional_parts)})"
    print(f"\n✅ Musikvideo konfiguriert:\n   {summary}\n")
