"""
Module for changing video categories in the target directory.

Allows searching for videos by title or ID and moving them to different category subdirectories.
Updates both the filesystem (rclone) and the metadata CSV index.
"""

import os
import subprocess
import traceback
from typing import List, Dict, Any, Optional
from .config import CONFIG, get_available_targets
from .module_search import check_csv_exists, search_videos
from .module_index import update_csv_with_video


def search_video_for_category_change(search_term: str) -> List[Dict[str, Any]]:
    """
    Search for videos by title or ID.
    
    Args:
        search_term: Title fragment or video ID (e.g., 'xYz123' or full 'youtube_xYz123')
    
    Returns:
        List of matching videos with metadata
    """
    csv_path = check_csv_exists()
    if not csv_path:
        raise FileNotFoundError("CSV-Datei nicht gefunden. Bitte führe zuerst eine Metadata-Indexierung durch.")
    
    # Search in both title and comment (which contains platform_id)
    results = search_videos(
        search_term,
        search_fields=['title', 'comment'],
        csv_path=csv_path,
        case_sensitive=False
    )
    
    return results


def extract_category_from_path(filepath: str) -> Optional[str]:
    """
    Extract the category (first subdirectory) from a video filepath.
    
    Args:
        filepath: Full rclone path like "remote:/Internetfilme/Patrick/Channel/video.m4v"
    
    Returns:
        Category name (e.g., "Patrick") or None if not found
    """
    # Remove rclone root prefix
    rclone_root = CONFIG.get("rclone_root", "")
    if not rclone_root:
        return None
    
    # Normalize paths for comparison
    filepath_normalized = filepath.strip()
    rclone_root_normalized = rclone_root.strip()
    
    # Remove trailing slash from root if present
    if rclone_root_normalized.endswith('/'):
        rclone_root_normalized = rclone_root_normalized[:-1]
    
    # Check if filepath starts with rclone_root
    if not filepath_normalized.startswith(rclone_root_normalized):
        return None
    
    # Remove the rclone_root prefix
    relative_path = filepath_normalized[len(rclone_root_normalized):]
    
    # Remove leading slash
    if relative_path.startswith('/'):
        relative_path = relative_path[1:]
    
    # Split path and get first component (category)
    parts = relative_path.split('/')
    if len(parts) >= 1 and parts[0]:  # Check that first part is not empty
        return parts[0]
    
    return None


def move_video_to_category(video_metadata: Dict[str, Any], new_category: str) -> bool:
    """
    Move a video file to a new category subdirectory on rclone.
    
    Args:
        video_metadata: Video metadata dictionary with filepath
        new_category: Target category name
    
    Returns:
        True if successful, False otherwise
    """
    old_filepath = video_metadata.get('filepath', '')
    if not old_filepath:
        print("❌ Fehler: Kein Dateipfad gefunden.")
        return False
    
    rclone_root = CONFIG.get('rclone_root', '')
    if not rclone_root:
        print("❌ Fehler: rclone_root nicht konfiguriert.")
        return False
    
    # Extract current path components
    # old_filepath format: "remote:/Internetfilme/Category/Channel/video.m4v"
    # We need to extract: Channel/video.m4v
    
    current_category = extract_category_from_path(old_filepath)
    if not current_category:
        print(f"❌ Fehler: Konnte aktuelle Kategorie nicht aus Pfad extrahieren: {old_filepath}")
        return False
    
    # Build relative path without category
    rclone_root_normalized = rclone_root.strip()
    if rclone_root_normalized.endswith('/'):
        rclone_root_normalized = rclone_root_normalized[:-1]
    
    filepath_after_root = old_filepath[len(rclone_root_normalized):].lstrip('/')
    
    # Remove current category from the path
    if filepath_after_root.startswith(current_category + '/'):
        relative_path_without_category = filepath_after_root[len(current_category) + 1:]
    else:
        print(f"❌ Fehler: Unerwartetes Pfadformat: {old_filepath}")
        return False
    
    # Build new path
    new_filepath = f"{rclone_root_normalized}/{new_category}/{relative_path_without_category}"
    
    print(f"\n📦 Verschiebe Video:")
    print(f"   Von: {old_filepath}")
    print(f"   Nach: {new_filepath}")
    
    # Use rclone moveto to move the file
    try:
        cmd = [
            "rclone", "moveto",
            old_filepath,
            new_filepath,
            "--progress"
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print("   ✅ Datei erfolgreich verschoben")
        
        # Update CSV index with new path
        print("   📝 Aktualisiere CSV-Index...")
        csv_updated = update_csv_with_video(new_filepath)
        if csv_updated:
            print("   ✅ CSV-Index aktualisiert")
        else:
            print("   ⚠️  CSV-Index konnte nicht aktualisiert werden")
            print("   💡 Führe eine vollständige Indexierung durch, um die CSV zu aktualisieren")
        
        return True
    
    except subprocess.CalledProcessError as e:
        print(f"   ❌ Fehler beim Verschieben: {e}")
        if e.stderr:
            print(f"   Fehlerdetails: {e.stderr}")
        return False
    except Exception as e:
        print(f"   ❌ Unerwarteter Fehler: {e}")
        return False


def interactive_category_change() -> None:
    """
    Interactive menu for changing video categories.
    """
    print("\n" + "=" * 80)
    print("📂 KATEGORIE ÄNDERN")
    print("=" * 80)
    print("\nSuche nach Titel oder ID, um die Kategorie zu ändern.")
    print()
    
    # Check if CSV exists
    csv_path = check_csv_exists()
    if not csv_path:
        print("⚠️  CSV-Datei nicht gefunden.")
        print("Möchtest du jetzt eine Indexierung durchführen?")
        
        confirm = input("Indexierung starten? [Y/n]: ").strip().lower()
        
        if confirm in ['', 'y', 'j', 'ja', 'yes']:
            from .module_index import index_server_videos
            
            print("\n🔄 Starte Indexierung...")
            try:
                csv_path = index_server_videos()
                if not csv_path:
                    print("\n❌ Indexierung fehlgeschlagen.")
                    return
                print(f"\n✅ Indexierung erfolgreich: {csv_path}")
            except Exception as e:
                print(f"\n❌ Fehler bei Indexierung: {e}")
                return
        else:
            print("\n⚠️  Abgebrochen. Kategorie-Änderung nicht möglich ohne CSV-Datei.")
            return
    
    # Main loop
    while True:
        print("\n" + "-" * 80)
        search_term = input("\nSuchbegriff (Titel oder ID) oder 'z' für Zurück: ").strip()
        
        if search_term.lower() == 'z':
            break
        
        if not search_term:
            print("⚠️  Kein Suchbegriff eingegeben.")
            continue
        
        try:
            # Search for videos
            print(f"\n🔍 Suche nach '{search_term}'...")
            results = search_video_for_category_change(search_term)
            
            if not results:
                print("❌ Keine Videos gefunden.")
                continue
            
            if len(results) > 1:
                print(f"\n⚠️  {len(results)} Videos gefunden. Bitte spezifiziere die Suche:")
                for i, video in enumerate(results[:10], 1):
                    category = extract_category_from_path(video.get('filepath', ''))
                    print(f"   {i}. {video.get('title', 'Unbekannt')} (Kategorie: {category})")
                
                if len(results) > 10:
                    print(f"   ... und {len(results) - 10} weitere")
                
                # Allow user to select one
                selection = input("\nWähle eine Nummer (1-10) oder 'z' für neue Suche: ").strip()
                
                if selection.lower() == 'z':
                    continue
                
                try:
                    idx = int(selection) - 1
                    if 0 <= idx < min(10, len(results)):
                        video = results[idx]
                    else:
                        print("⚠️  Ungültige Auswahl.")
                        continue
                except ValueError:
                    print("⚠️  Ungültige Eingabe.")
                    continue
            else:
                video = results[0]
            
            # Display video details
            print("\n" + "=" * 80)
            print(f"📹 Video gefunden:")
            print(f"   Titel:    {video.get('title', 'Unbekannt')}")
            print(f"   Künstler: {video.get('artist', 'Unbekannt')}")
            print(f"   Genre:    {video.get('genre', 'Unbekannt')}")
            print(f"   Pfad:     {video.get('filepath', 'Unbekannt')}")
            
            current_category = extract_category_from_path(video.get('filepath', ''))
            if not current_category:
                print("❌ Fehler: Konnte aktuelle Kategorie nicht ermitteln.")
                continue
            
            print(f"\n   Aktuelle Kategorie: {current_category}")
            print("=" * 80)
            
            # Get available categories
            all_categories = get_available_targets()
            
            # Remove current category from list
            available_categories = [cat for cat in all_categories if cat != current_category]
            
            if not available_categories:
                print("⚠️  Keine anderen Kategorien verfügbar.")
                continue
            
            # Display available categories
            print("\n📂 Verfügbare Kategorien:")
            for i, category in enumerate(available_categories, 1):
                print(f"   {i}. {category}")
            print("   z. Zurück")
            
            # Get user choice
            choice = input(f"\nKategorie wählen (1-{len(available_categories)}) oder 'z' für Zurück: ").strip()
            
            if choice.lower() == 'z':
                continue
            
            try:
                cat_idx = int(choice) - 1
                if 0 <= cat_idx < len(available_categories):
                    new_category = available_categories[cat_idx]
                else:
                    print("⚠️  Ungültige Auswahl.")
                    continue
            except ValueError:
                print("⚠️  Ungültige Eingabe.")
                continue
            
            # Confirm change
            print(f"\n⚠️  Ändere Kategorie von '{current_category}' zu '{new_category}'")
            confirm = input("Fortfahren? [Y/n]: ").strip().lower()
            
            if confirm not in ['', 'y', 'j', 'ja', 'yes']:
                print("   Abgebrochen.")
                continue
            
            # Perform the move
            success = move_video_to_category(video, new_category)
            
            if success:
                print(f"\n✅ Kategorie erfolgreich geändert!")
                print(f"   {video.get('title', 'Video')} ist jetzt in '{new_category}'")
            else:
                print(f"\n❌ Kategorie-Änderung fehlgeschlagen.")
            
            # Ask if user wants to change another video
            another = input("\nWeiteres Video ändern? [Y/n]: ").strip().lower()
            if another not in ['', 'y', 'j', 'ja', 'yes']:
                break
        
        except FileNotFoundError as e:
            print(f"\n❌ {e}")
            break
        
        except Exception as e:
            print(f"\n❌ Fehler: {e}")
            if CONFIG.get('debug_mode', False):
                traceback.print_exc()
