"""
Video Search Module

Provides search functionality for video files based on metadata stored in CSV files.
Supports searching by title, keywords, description, and album.
"""

import os
import csv
import traceback
from typing import List, Dict, Any, Optional
from .config import CONFIG


def check_csv_exists(work_dir: Optional[str] = None) -> Optional[str]:
    """
    Check if the metadata CSV file exists.
    
    Args:
        work_dir: Optional work directory path. Uses CONFIG if not provided.
    
    Returns:
        Path to CSV file if it exists, None otherwise
    """
    if not work_dir:
        work_dir = CONFIG.get("work_dir")
    
    if not work_dir:
        return None
    
    csv_path = os.path.join(work_dir, "video_metadata_index.csv")
    
    if os.path.exists(csv_path):
        return csv_path
    
    return None


def search_videos(
    search_term: str,
    search_fields: Optional[List[str]] = None,
    csv_path: Optional[str] = None,
    case_sensitive: bool = False
) -> List[Dict[str, Any]]:
    """
    Search for videos in the metadata CSV file.
    
    Args:
        search_term: Term to search for
        search_fields: List of fields to search in. 
                      Defaults to ['title'] for full-text search.
                      Options: 'title', 'grouping', 'description', 
                               'long_description', 'album'
        csv_path: Optional path to CSV file. Uses default location if not provided.
        case_sensitive: Whether search should be case-sensitive (default: False)
    
    Returns:
        List of matching video metadata dictionaries
    """
    # Default to title search (full-text default)
    if search_fields is None:
        search_fields = ['title']
    
    # Get CSV path
    if not csv_path:
        csv_path = check_csv_exists()
    
    if not csv_path or not os.path.exists(csv_path):
        raise FileNotFoundError("CSV-Datei nicht gefunden. Bitte führe zuerst eine Metadata-Indexierung durch.")
    
    # Prepare search term
    if not case_sensitive:
        search_term = search_term.lower()
    
    results = []
    
    # Read and search CSV
    try:
        with open(csv_path, 'r', newline='', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            
            for row in reader:
                # Skip rows with errors
                if 'error' in row and row.get('error'):
                    continue
                
                # Check if search term matches any of the specified fields
                match = False
                for field in search_fields:
                    field_value = row.get(field, '')
                    
                    # Prepare field value for comparison
                    if not case_sensitive:
                        field_value = field_value.lower()
                    
                    # Check for match
                    if search_term in field_value:
                        match = True
                        break
                
                if match:
                    results.append(row)
    
    except Exception as e:
        raise RuntimeError(f"Fehler beim Lesen der CSV-Datei: {e}")
    
    return results


def search_by_keywords(search_term: str, csv_path: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    Search videos by keywords (Grouping field).
    Keywords are separated by " / " in the Grouping field.
    
    Args:
        search_term: Keyword to search for
        csv_path: Optional path to CSV file
    
    Returns:
        List of matching video metadata dictionaries
    """
    return search_videos(search_term, search_fields=['grouping'], csv_path=csv_path)


def search_by_description(search_term: str, csv_path: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    Search videos by description (both short and long descriptions).
    
    Args:
        search_term: Term to search for in descriptions
        csv_path: Optional path to CSV file
    
    Returns:
        List of matching video metadata dictionaries
    """
    return search_videos(
        search_term, 
        search_fields=['description', 'long_description'], 
        csv_path=csv_path
    )


def search_by_album(search_term: str, csv_path: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    Search videos by album name.
    
    Args:
        search_term: Album name to search for
        csv_path: Optional path to CSV file
    
    Returns:
        List of matching video metadata dictionaries
    """
    return search_videos(search_term, search_fields=['album'], csv_path=csv_path)


def search_by_title(search_term: str, csv_path: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    Search videos by title (full-text search).
    This is the default search method.
    
    Args:
        search_term: Term to search for in titles
        csv_path: Optional path to CSV file
    
    Returns:
        List of matching video metadata dictionaries
    """
    return search_videos(search_term, search_fields=['title'], csv_path=csv_path)


def format_search_results(results: List[Dict[str, Any]], max_results: int = 50) -> str:
    """
    Format search results for display.
    
    Args:
        results: List of matching video metadata dictionaries
        max_results: Maximum number of results to display (default: 50)
    
    Returns:
        Formatted string for display
    """
    if not results:
        return "Keine Ergebnisse gefunden."
    
    output = []
    output.append(f"\n{'=' * 80}")
    output.append(f"🔍 SUCHERGEBNISSE: {len(results)} Video(s) gefunden")
    output.append("=" * 80)
    
    # Limit results
    displayed = results[:max_results]
    if len(results) > max_results:
        output.append(f"\n⚠️  Zeige nur die ersten {max_results} von {len(results)} Ergebnissen.")
    
    for i, result in enumerate(displayed, 1):
        output.append(f"\n[{i}] {result.get('title', 'Unbekannter Titel')}")
        output.append(f"    Pfad:        {result.get('filepath', 'N/A')}")
        
        # Show relevant fields
        if result.get('artist'):
            output.append(f"    Künstler:    {result.get('artist')}")
        if result.get('album'):
            output.append(f"    Album:       {result.get('album')}")
        if result.get('genre'):
            output.append(f"    Genre:       {result.get('genre')}")
        if result.get('year'):
            output.append(f"    Jahr:        {result.get('year')}")
        if result.get('duration'):
            try:
                duration_sec = float(result.get('duration', 0))
                minutes = int(duration_sec // 60)
                seconds = int(duration_sec % 60)
                output.append(f"    Dauer:       {minutes}:{seconds:02d} min")
            except (ValueError, TypeError):
                pass
        if result.get('description'):
            desc = result.get('description')
            if len(desc) > 80:
                desc = desc[:77] + "..."
            output.append(f"    Beschreibung: {desc}")
        if result.get('grouping'):
            keywords = result.get('grouping')
            if len(keywords) > 80:
                keywords = keywords[:77] + "..."
            output.append(f"    Keywords:    {keywords}")
    
    if len(results) > max_results:
        output.append(f"\n⚠️  ... und {len(results) - max_results} weitere Ergebnisse")
    
    output.append("\n" + "=" * 80)
    
    return "\n".join(output)


def interactive_search_menu() -> None:
    """
    Interactive search menu for the CLI.
    Provides options to search by different criteria.
    """
    # Check if CSV exists
    csv_path = check_csv_exists()
    
    if not csv_path:
        print("\n" + "=" * 80)
        print("⚠️  CSV-DATEI NICHT GEFUNDEN")
        print("=" * 80)
        print("\nDie Metadata-Index CSV-Datei wurde nicht gefunden.")
        print("Möchtest du jetzt eine Indexierung durchführen?")
        print()
        
        confirm = input("Indexierung starten? [Y/n]: ").strip().lower()
        
        if confirm in ['', 'y', 'j', 'ja', 'yes']:
            # Import here to avoid circular dependency
            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.")
                    input("\n[ENTER] zum Fortfahren...")
                    return
                print(f"\n✅ Indexierung erfolgreich: {csv_path}")
            except Exception as e:
                print(f"\n❌ Fehler bei Indexierung: {e}")
                input("\n[ENTER] zum Fortfahren...")
                return
        else:
            print("\n⚠️  Abgebrochen. Suche nicht möglich ohne CSV-Datei.")
            input("\n[ENTER] zum Fortfahren...")
            return
    
    # Main search loop
    while True:
        print("\n" + "=" * 80)
        print("🔍 VIDEO-SUCHE")
        print("=" * 80)
        print("\nSuchoptionen:")
        print("1. 📝 Volltextsuche (Titel) - Default")
        print("2. 🏷️  Schlüsselwörter (Keywords/Tags)")
        print("3. 📄 Beschreibung (kurz + lang)")
        print("4. 💿 Album")
        print("5. 🔍 Erweiterte Suche (mehrere Felder)")
        print("z. Zurück")
        
        choice = input("\nAuswahl: ").strip().lower()
        
        if choice == 'z':
            break
        
        # Get search term
        search_term = input("\nSuchbegriff: ").strip()
        
        if not search_term:
            print("⚠️  Kein Suchbegriff eingegeben.")
            continue
        
        try:
            results = []
            
            if choice == '1' or choice == '':
                print(f"\n🔍 Suche nach '{search_term}' in Titeln...")
                results = search_by_title(search_term, csv_path)
            
            elif choice == '2':
                print(f"\n🔍 Suche nach '{search_term}' in Schlüsselwörtern...")
                results = search_by_keywords(search_term, csv_path)
            
            elif choice == '3':
                print(f"\n🔍 Suche nach '{search_term}' in Beschreibungen...")
                results = search_by_description(search_term, csv_path)
            
            elif choice == '4':
                print(f"\n🔍 Suche nach '{search_term}' in Alben...")
                results = search_by_album(search_term, csv_path)
            
            elif choice == '5':
                print(f"\n🔍 Erweiterte Suche nach '{search_term}' in allen Feldern...")
                results = search_videos(
                    search_term,
                    search_fields=['title', 'grouping', 'description', 'long_description', 'album'],
                    csv_path=csv_path
                )
            
            else:
                print("⚠️  Ungültige Auswahl.")
                continue
            
            # Display results
            print(format_search_results(results))
            
            input("\n[ENTER] zum Fortfahren...")
        
        except FileNotFoundError as e:
            print(f"\n❌ {e}")
            input("\n[ENTER] zum Fortfahren...")
            break
        
        except Exception as e:
            print(f"\n❌ Fehler bei der Suche: {e}")
            if CONFIG.get('debug_mode', False):
                traceback.print_exc()
            input("\n[ENTER] zum Fortfahren...")
