"""
Genre Classification Module

Provides strict single-choice genre classification for internet videos.
Defines the 12 standard genres and validation logic to ensure consistency
and eliminate "Wildwuchs" in genre assignments.
"""

from enum import Enum
from typing import Optional, List, Tuple


class StandardGenre(Enum):
    """
    The 12 standard genres for internet video classification.
    Each video must be assigned to exactly one of these genres.
    """
    KINDER_FAMILIE = "Kinder & Familie"
    FINANZEN_BUSINESS = "Finanzen & Business"
    BILDUNG_WISSEN = "Bildung & Wissen"
    TECHNIK_IT = "Technik & IT"
    ANLEITUNG_DIY = "Anleitung & DIY"
    NACHRICHTEN_POLITIK = "Nachrichten & Politik"
    UNTERHALTUNG = "Unterhaltung"
    LIFESTYLE_VLOGS = "Lifestyle & Vlogs"
    SPORT_FITNESS = "Sport & Fitness"
    GAMING = "Gaming"
    KUNST_KULTUR = "Kunst & Kultur"
    GESUNDHEIT_PSYCHOLOGIE = "Gesundheit & Psychologie"


# Fallback genre for uncategorized content
UNCATEGORIZED_GENRE = "Unkategorisiert"


def get_all_genre_names() -> List[str]:
    """
    Returns a list of all valid genre names.
    
    Returns:
        List of genre names as strings
    """
    return [genre.value for genre in StandardGenre]


def get_genre_rules_prompt() -> str:
    """
    Returns the prompt section with genre classification rules for the AI.
    This should be included in the Claude API prompt.
    
    Returns:
        Formatted string with genre rules and list
    """
    genre_list = "\n".join([f"   • {genre.value}" for genre in StandardGenre])
    
    return f"""
=== GENRE-KLASSIFIZIERUNG (KRITISCH) ===

Das Genre-Feld MUSS exakt einem der folgenden 12 vordefinierten Genres entsprechen:

{genre_list}

WICHTIGE REGELN:
1. Wähle EXAKT EINEN Begriff aus der obigen Liste
2. Verwende die exakte Schreibweise (inklusive "&" und Groß-/Kleinschreibung)
3. Wenn mehrere Genres passen, wähle den PRIMÄREN FOKUS des Videos
4. KEINE anderen Begriffe oder Formate (z.B. "Dokumentation", "Tutorial", "Vlog") verwenden
5. Diese Begriffe gehören zu den Tags/Keywords, NICHT zum Genre

BEISPIELE:
- Video über Aktien-Tipps → "Finanzen & Business" (auch wenn es ein Erklärvideo ist)
- Programmier-Tutorial → "Technik & IT" (nicht "Bildung & Wissen", auch wenn lehrreich)
- Koch-Anleitung → "Anleitung & DIY"
- Peppa Wutz Episode → "Kinder & Familie"
- Fitness-Workout → "Sport & Fitness"
- Politische Talkshow → "Nachrichten & Politik"
- Gaming Let's Play → "Gaming"
- Kunstmuseum-Führung → "Kunst & Kultur"
- Meditation & Achtsamkeit → "Gesundheit & Psychologie"
- Daily Vlog → "Lifestyle & Vlogs"
- Stand-up Comedy → "Unterhaltung"
- Wissenschaftsdoku über Physik → "Bildung & Wissen"

TRENNUNG VON GENRE UND FORMAT:
- "Dokumentation", "Tutorial", "Vlog", "Interview" sind FORMATE → gehören zu den Keywords
- Das Genre beschreibt das THEMA, nicht die Form
"""


def validate_genre(genre: str) -> Tuple[bool, Optional[str]]:
    """
    Validates if the provided genre is in the list of standard genres.
    
    Args:
        genre: The genre string to validate
        
    Returns:
        Tuple of (is_valid, validated_genre_or_none)
        - If valid: (True, genre)
        - If invalid: (False, None)
    """
    if not genre:
        return False, None
    
    # Normalize for comparison (strip whitespace)
    genre_normalized = genre.strip()
    
    # Check exact match
    valid_genres = get_all_genre_names()
    if genre_normalized in valid_genres:
        return True, genre_normalized
    
    # Check case-insensitive match (in case AI returns wrong case)
    genre_lower = genre_normalized.lower()
    for valid_genre in valid_genres:
        if valid_genre.lower() == genre_lower:
            # Return the correct capitalization
            return True, valid_genre
    
    return False, None


def get_validated_genre(ai_genre: Optional[str], fallback_to_uncategorized: bool = True) -> str:
    """
    Gets a validated genre from AI output, with optional fallback.
    
    Args:
        ai_genre: The genre returned by the AI
        fallback_to_uncategorized: If True, returns "Unkategorisiert" for invalid genres.
                                    If False, returns the original invalid genre.
        
    Returns:
        A valid genre string (either validated or fallback)
    """
    if not ai_genre:
        return UNCATEGORIZED_GENRE if fallback_to_uncategorized else "Internet"
    
    is_valid, validated = validate_genre(ai_genre)
    
    if is_valid:
        return validated
    
    # Invalid genre
    if fallback_to_uncategorized:
        print(f"   ⚠️  Ungültiges Genre von AI: '{ai_genre}'")
        print(f"   ℹ️  Setze Genre auf '{UNCATEGORIZED_GENRE}'")
        return UNCATEGORIZED_GENRE
    else:
        return ai_genre


def get_genre_list_for_display() -> str:
    """
    Returns a formatted string of all genres for display in the UI.
    
    Returns:
        Formatted string with numbered genre list
    """
    genres = get_all_genre_names()
    return "\n".join([f"{i+1:2d}. {genre}" for i, genre in enumerate(genres)])
