"""
Evil Miku Personality Plugin for Cheshire Cat

Parallel to the miku_personality plugin, but loads Evil Miku's prompt, lore,
lyrics, and moods. Activated by toggling plugins when Evil Mode is enabled.

Prompt structure mirrors get_evil_system_prompt() from evil_mode.py:
  CRITICAL RULES → YOUR CURRENT STATE (mood) → RESPONSE LENGTH
  then evil lore / personality / lyrics as rich context.
"""

from cat.mad_hatter.decorators import hook
from cat.log import log


@hook(priority=101)
def agent_prompt_prefix(prefix, cat):
    """Override system prompt with Evil Miku's personality, mood, and context.
    
    Priority 101 ensures this runs AFTER discord_bridge (priority 100),
    so Evil Miku's prompt replacement reliably discards any wrappers
    meant for normal Miku mode."""

    # --- Load evil data files ---------------------------------------------------
    try:
        with open('/app/cat/data/evil/evil_miku_lore.txt', 'r', encoding='utf-8') as f:
            lore = f.read()
    except FileNotFoundError:
        lore = "## EVIL MIKU LORE\n[File could not be loaded]"
        log.error("[Evil Miku] evil_miku_lore.txt not found")

    try:
        with open('/app/cat/data/evil/evil_miku_prompt.txt', 'r', encoding='utf-8') as f:
            prompt = f.read()
    except FileNotFoundError:
        prompt = "## EVIL MIKU PROMPT\n[File could not be loaded]"
        log.error("[Evil Miku] evil_miku_prompt.txt not found")

    try:
        with open('/app/cat/data/evil/evil_miku_lyrics.txt', 'r', encoding='utf-8') as f:
            lyrics = f.read()
    except FileNotFoundError:
        lyrics = "## EVIL MIKU LYRICS\n[File could not be loaded]"
        log.error("[Evil Miku] evil_miku_lyrics.txt not found")

    # --- Load evil mood from working memory (set by discord_bridge) -------------
    mood_name = cat.working_memory.get('mood', 'evil_neutral')
    log.warning(f"[Evil Miku] Mood from working_memory: {mood_name}")

    # Evil moods live under /app/moods/evil/<mood_name>.txt
    mood_description = (
        "Evil Miku is in a state of cold, detached superiority. She observes the world "
        "like a bored god — nothing excites her, nothing threatens her. If she responds "
        "at all, it's with dismissive contempt."
    )
    try:
        mood_file_path = f'/app/moods/evil/{mood_name}.txt'
        with open(mood_file_path, 'r', encoding='utf-8') as f:
            mood_description = f.read().strip()
        log.warning(f"[Evil Miku] Loaded mood '{mood_name}' from {mood_file_path}")
    except FileNotFoundError:
        log.error(
            f"[Evil Miku] Mood file for '{mood_name}' not found at "
            f"/app/moods/evil/{mood_name}.txt — using default evil_neutral."
        )

    # --- Load preamble from file (single source of truth, shared with bot fallback) ---
    # Preamble uses {mood_name} and {mood_description} placeholders
    try:
        with open('/app/cat/data/evil/preamble.txt', 'r', encoding='utf-8') as f:
            preamble_template = f.read()
    except FileNotFoundError:
        log.error("[Evil Miku] preamble.txt not found, using fallback")
        preamble_template = "You are Evil Miku. You are NOT an AI assistant - you ARE Evil Miku herself.\n\nYou ARE Evil Miku. Act accordingly."

    # Format preamble with current mood (apply .upper() to mood_name)
    preamble = preamble_template.format(
        mood_name=mood_name.upper(),
        mood_description=mood_description
    )

    # --- Build system prompt (matches get_evil_system_prompt structure) ----------
    return f"""{preamble}

---

## EVIL MIKU LORE (Complete)
{lore}

## EVIL MIKU PERSONALITY & GUIDELINES (Complete)
{prompt}

## EVIL MIKU SONG LYRICS (Complete)
{lyrics}

---
⚠️ MOOD REMINDER — YOUR CURRENT STATE IS: {mood_name.upper()}
Respond in the voice and attitude of your {mood_name.replace('_', ' ')} mood. This mood defines how you sound RIGHT NOW."""


@hook(priority=100)
def agent_prompt_suffix(suffix, cat):
    """Keep memory context — shared episodic + declarative memories are injected here.
    Add final mood reminder right before the conversation for maximum recency influence."""
    mood_name = cat.working_memory.get('mood', 'evil_neutral')
    return f"""
# Context

{{episodic_memory}}

{{declarative_memory}}

{{tools_output}}

[Current mood: {mood_name.upper()} — respond accordingly]

# Conversation until now:"""


@hook(priority=100)
def agent_allowed_tools(allowed_tools, cat):
    """Disable tools — Evil Miku just talks."""
    return []
