# wcs/games/moderator_styles/__init__.py
"""
Moderator style loader.

Loads style definitions from .md files at runtime.
Each style defines both LLM persona (for system prompt) and TTS instructions.
"""

import os
import xbmcaddon


# Style index -> filename mapping (matches settings.xml order)
STYLE_FILES = [
    "dramatic.md",     # 0: Dramatický moderátor
    "friendly.md",     # 1: Vřelý průvodce
    "comedian.md",     # 2: Hravý komik
    "professional.md", # 3: Profesionální vypravěč
    "mysterious.md",   # 4: Tajemný vypravěč
]

# Base directory (same folder as this __init__.py)
_STYLES_DIR = os.path.dirname(os.path.abspath(__file__))


def _load_style_file(filename):
    """Load raw content of a style .md file.

    Args:
        filename: Name of the .md file in moderator_styles/.

    Returns:
        Full file content as string, or empty string on error.
    """
    path = os.path.join(_STYLES_DIR, filename)
    try:
        with open(path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception:
        return ""


def _extract_section(content, section_name):
    """Extract content of a ## section from markdown.

    Args:
        content: Full markdown content.
        section_name: Name of the section (without ##).

    Returns:
        Section content as string (without the heading line).
    """
    lines = content.split("\n")
    capturing = False
    result = []
    for line in lines:
        if line.startswith("## ") and section_name in line:
            capturing = True
            continue
        elif line.startswith("## ") and capturing:
            break
        elif capturing:
            result.append(line)
    return "\n".join(result).strip()


def get_current_style_index():
    """Get the current moderator style index from addon settings.

    Returns:
        int: Style index (0-4), defaults to 0.
    """
    try:
        addon = xbmcaddon.Addon()
        value = addon.getSetting("milionar_moderator_style")
        return int(value) if value else 0
    except Exception:
        return 0


def load_style(style_index=None):
    """Load a moderator style definition.

    Args:
        style_index: Style index (0-4). If None, loads from settings.

    Returns:
        dict with keys: persona, tone, vocabulary, pacing, tts_instructions, raw
    """
    if style_index is None:
        style_index = get_current_style_index()

    # Clamp to valid range
    style_index = max(0, min(style_index, len(STYLE_FILES) - 1))
    filename = STYLE_FILES[style_index]
    content = _load_style_file(filename)

    return {
        "persona": _extract_section(content, "Moderator Persona"),
        "tone": _extract_section(content, "Tone"),
        "vocabulary": _extract_section(content, "Vocabulary"),
        "pacing": _extract_section(content, "Pacing"),
        "tts_instructions": _extract_section(content, "TTS Instructions"),
        "raw": content,
    }


def get_style_prompt_block(style_index=None):
    """Build the moderator style block for injection into system prompt.

    This replaces the hardcoded moderator personality description.
    Returns a formatted string ready for prompt injection.

    Args:
        style_index: Style index (0-4). If None, loads from settings.

    Returns:
        Formatted moderator style block as string.
    """
    style = load_style(style_index)

    parts = []
    if style["persona"]:
        parts.append(style["persona"])
    if style["tone"]:
        parts.append("TÓN A EMOCE:\n{}".format(style["tone"]))
    if style["vocabulary"]:
        parts.append("SLOVNÍK A FORMULACE:\n{}".format(style["vocabulary"]))
    if style["pacing"]:
        parts.append("TEMPO A RYTMUS:\n{}".format(style["pacing"]))

    return "\n\n".join(parts)


def get_tts_instructions(style_index=None):
    """Get TTS voice instructions for the current style.

    Args:
        style_index: Style index (0-4). If None, loads from settings.

    Returns:
        English TTS instructions string.
    """
    style = load_style(style_index)
    return style["tts_instructions"] or (
        "Energetic, dramatic delivery. Build suspense with pauses before reveals. "
        "Sound like a charismatic TV quiz show host keeping the audience engaged."
    )
