import os
import shutil
import json
from .config import CONFIG, update_config
from .utils import run_shell, get_state
from .module_index import update_csv_with_video

def deploy(job_dir):
    state = get_state(job_dir)
    
    final_name = state.get("final_name")
    m4v_file = os.path.join(job_dir, f"{final_name}.m4v")
    
    # DMG Suche: Wir nehmen einfach das erste .dmg File im Ordner (es sollte nur eins geben)
    dmg_file = None
    dmg_filename = ""
    for f in os.listdir(job_dir):
        if f.endswith(".dmg"):
            dmg_file = os.path.join(job_dir, f)
            dmg_filename = f
            break

    json_path = os.path.join(job_dir, "original.info.json")
    
    if not os.path.exists(m4v_file):
        # Prüfung: Wenn wir im "nur-Video-Modus" sind oder Video schon weg ist
        pass # Exception kommt unten erst bei Bedarf oder wir skippen
    
    # --- 1. ZIEL & PFADE ---
    target_name = state.get("target", "Patrick")
    
    # Safety check: "Auto" should have been resolved during curation
    if target_name == "Auto":
        print("   ⚠️  Target ist noch 'Auto' - sollte während der Kuratierung aufgelöst worden sein")
        print("   ℹ️  Fallback zum ersten verfügbaren Ziel")
        from .config import get_available_targets
        targets = get_available_targets()
        if targets:
            target_name = targets[0]
            print(f"   ℹ️  Verwende Fallback-Ziel: {target_name}")
        else:
            raise Exception("Keine verfügbaren Zielverzeichnisse in der Config!")
    
    rclone_root = CONFIG.get("rclone_root")
    rclone_master_root = CONFIG.get("rclone_master_root") or rclone_root
    
    if not rclone_root:
        raise Exception("Kein 'rclone_root' in Config definiert!")

    # --- KANAL ORDNER BERECHNEN (GEHÄRTET) ---
    channel_folder = "Unknown"
    
    # 1. Priorität: Sampler-Name (bei Musikvideos)
    if state.get("curated_album"):
        channel_folder = state.get("curated_album")
        
    # 2. Priorität: Kanalname (bei normalen Videos)
    elif os.path.exists(json_path):
        try:
            with open(json_path, "r") as f:
                meta = json.load(f)
                channel_folder = meta.get("channel") or meta.get("uploader") or "Unknown"
        except: pass

    # FIX: Entferne ' und " aus dem Ordnernamen, um Shell-Fehler zu vermeiden
    channel_folder = channel_folder.replace("/", "_").replace("\\", "_")\
                                   .replace("'", "").replace('"', "").strip()
            
    # JAHR BESTIMMEN (für Master Archiv)
    # Prio 1: Aus DMG Namen (YYYY-...)
    # Prio 2: Aus final_name (falls Internetvideo)
    year_folder = "Unknown_Year"
    if dmg_filename and dmg_filename[:4].isdigit():
        year_folder = dmg_filename[:4]
    elif final_name and final_name[:4].isdigit():
        year_folder = final_name[:4]

    # A. Video (Emby): {MediaRoot}/{Target}/{Kanalname}/
    m4v_remote_path = f"{rclone_root}/{target_name}/{channel_folder}"
    
    # B. Master (Archiv): {ArchiveRoot}/{JAHR}/ (OHNE Person!)
    master_remote_path = f"{rclone_master_root}/{year_folder}"
    
    # Rclone flags for upload
    rclone_flags = "--progress"
    
    # --- 2. UPLOAD ---
    print(f"\n🚀 Upload Video nach: {m4v_remote_path}")
    
    # Check ob m4v noch da ist (falls vorheriger Run abgebrochen ist)
    if os.path.exists(m4v_file):
        # Video: copy + remove (statt move, für maximale Stabilität)
        if run_shell(f"rclone copy '{m4v_file}' '{m4v_remote_path}/' {rclone_flags}"):
             os.remove(m4v_file)
             
             # Upload fanart sidecar if present
             fanart_src = os.path.join(job_dir, "fanart.jpg")
             if os.path.exists(fanart_src):
                 fanart_file = os.path.join(job_dir, f"{final_name}-fanart.jpg")
                 os.rename(fanart_src, fanart_file)
                 print(f"   🖼️  Upload Fanart: {os.path.basename(fanart_file)}")
                 if run_shell(f"rclone copy '{fanart_file}' '{m4v_remote_path}/' {rclone_flags}"):
                     os.remove(fanart_file)
             
             # Prepare DMG remote path if DMG exists
             dmg_remote_full_path = None
             if dmg_file and os.path.exists(dmg_file):
                 dmg_remote_full_path = f"{master_remote_path}/{dmg_filename}"
             
             # Update CSV index after successful upload
             video_filename = os.path.basename(m4v_file)
             video_remote_full_path = f"{m4v_remote_path}/{video_filename}"
             print(f"📝 Aktualisiere CSV-Index...")
             csv_updated = update_csv_with_video(video_remote_full_path, dmg_remote_full_path)
             if not csv_updated:
                 print("   ⚠️  CSV-Index konnte nicht aktualisiert werden (Deployment war aber erfolgreich)")
    else:
        print("   ⚠️  M4V Datei lokal nicht gefunden (bereits hochgeladen?). Überspringe Video-Upload.")
    
    if dmg_file and os.path.exists(dmg_file):
        print(f"   Archiviere Master nach: {master_remote_path}")
        # Master: copy + remove
        if run_shell(f"rclone copy '{dmg_file}' '{master_remote_path}/' {rclone_flags}"):
             os.remove(dmg_file)
    
    # --- 3. CLEANUP ---
    print("   Räume Arbeitsverzeichnis auf...")
    shutil.rmtree(job_dir)
    print("✅ Job abgeschlossen & gelöscht.")
    
    # --- 4. CLASSIFICATION RULES UPDATE CHECK ---
    # Increment video counter and check if we should re-learn rules
    if CONFIG.get("classification_enabled", False):
        videos_since_update = CONFIG.get("videos_since_last_rule_update", 0)
        videos_since_update += 1
        threshold = CONFIG.get("classification_rules_threshold", 10)
        
        # Update counter - persisting is necessary for intermittent tool usage
        update_config("videos_since_last_rule_update", videos_since_update)
        
        # Check if threshold reached
        if videos_since_update >= threshold:
            print(f"\n🧠 Schwellenwert erreicht ({videos_since_update}/{threshold} Videos)")
            print("   Lerne Klassifikationsregeln neu...")
            
            should_reset_counter = True  # Reset counter regardless of success/failure
            try:
                from .module_classification_rules import learn_classification_rules
                success = learn_classification_rules()
                if success:
                    print("   ✅ Regeln erfolgreich aktualisiert!")
                else:
                    print("   ⚠️  Fehler beim Lernen der Regeln.")
            except Exception as e:
                print(f"   ⚠️  Fehler beim Lernen der Regeln: {e}")
            finally:
                # Always reset counter to avoid repeated failures
                if should_reset_counter:
                    update_config("videos_since_last_rule_update", 0)