"""
Prompt loader with versioning and channel support.

Usage:
    from prompts import get_prompt
    prompt_template = get_prompt("layer4a_concept", version="v1")

    # Fill in the template
    filled_prompt = prompt_template.format(
        channel_name="...",
        channel_description="...",
        ...
    )

    # For v4 (Director + Evaluator architecture):
    from prompts import get_prompt, get_revision_template
    director_prompt = get_prompt("layer4_director", version="v4")
    evaluator_prompt = get_prompt("layer4_evaluator", version="v4")
    revision_section = get_revision_template("v4")  # For revision passes

    # For v4 with channel-specific prompts:
    from prompts import get_channel_director_prompt
    prompt = get_channel_director_prompt("why_you_do_that", **template_vars)
"""

import importlib
from typing import Optional


# Channel IDs that have dedicated director prompts
CHANNEL_SPECIFIC_DIRECTORS = [
    "why_you_do_that",
    "how_it_actually_works",
    "sixty_second_rabbit_hole",
    "designed_to_trick_you",
    "the_money_thing",
    "what_happens_next",
    "one_minute_history"
]


def get_prompt(prompt_name: str, version: str = "v1", channel: Optional[str] = None) -> str:
    """
    Load a prompt template by name and version.

    Args:
        prompt_name: One of:
            - v1/v2/v3: "layer4a_concept", "layer4b_script", "layer4c_visual",
                        "layer4b_production_spec", "layer4c_asset_specs"
            - v4: "layer4_director", "layer4_evaluator"
        version: Prompt version (default "v1")
        channel: For v4 director, optionally specify channel for channel-specific prompt

    Returns:
        The prompt template string with {placeholder} variables
    """
    # For v4 director with channel-specific prompts
    if prompt_name == "layer4_director" and version == "v4" and channel in CHANNEL_SPECIFIC_DIRECTORS:
        module_name = f"prompts.prompt_v4.layer4_director_{channel}"
        try:
            module = importlib.import_module(module_name)
            # Channel-specific prompts have get_prompt() function, not PROMPT constant
            if hasattr(module, 'get_prompt'):
                # Return a marker that indicates this needs to be called with kwargs
                return f"__CHANNEL_SPECIFIC__:{channel}"
            return module.PROMPT
        except ImportError:
            # Fall back to unified prompt
            pass

    module_name = f"prompts.prompt_{version}.{prompt_name}"
    module = importlib.import_module(module_name)
    return module.PROMPT


def get_channel_director_prompt(channel_id: str, **kwargs) -> str:
    """
    Get a fully formatted channel-specific director prompt.

    This is the primary interface for v4 channel-specific prompts.
    It loads the channel's prompt module and calls get_prompt() with
    all the template variables.

    Args:
        channel_id: One of the CHANNEL_SPECIFIC_DIRECTORS
        **kwargs: Template variables (premise, research_report_content, etc.)
                  Note: channel_id in kwargs will be ignored (use positional arg)

    Returns:
        Fully formatted prompt string ready to send to Claude

    Raises:
        ImportError: If channel doesn't have a specific prompt
    """
    # Remove channel_id from kwargs if passed (use positional arg instead)
    kwargs.pop("channel_id", None)

    if channel_id not in CHANNEL_SPECIFIC_DIRECTORS:
        raise ValueError(f"No channel-specific prompt for '{channel_id}'. "
                        f"Valid channels: {CHANNEL_SPECIFIC_DIRECTORS}")

    module_name = f"prompts.prompt_v4.layer4_director_{channel_id}"
    module = importlib.import_module(module_name)

    if hasattr(module, 'get_prompt'):
        return module.get_prompt(**kwargs)
    else:
        raise AttributeError(f"Module {module_name} missing get_prompt() function")


def get_prompt_metadata(prompt_name: str, version: str = "v1", channel: Optional[str] = None) -> dict:
    """
    Get metadata about a prompt (for tracking in output).

    Args:
        prompt_name: Prompt name (see get_prompt for options)
        version: Prompt version (default "v1")
        channel: For v4 director, optionally specify channel

    Returns:
        Dict with version, layer, model, description
    """
    # For channel-specific prompts
    if prompt_name == "layer4_director" and version == "v4" and channel in CHANNEL_SPECIFIC_DIRECTORS:
        module_name = f"prompts.prompt_v4.layer4_director_{channel}"
        try:
            module = importlib.import_module(module_name)
            return getattr(module, "METADATA", {"version": version, "name": prompt_name, "channel": channel})
        except ImportError:
            pass

    module_name = f"prompts.prompt_{version}.{prompt_name}"
    module = importlib.import_module(module_name)
    return getattr(module, "METADATA", {"version": version, "name": prompt_name})


def get_revision_template(version: str = "v4") -> str:
    """
    Get the revision section template for v4+ Director prompts.

    This template is inserted into the Director prompt when revision
    instructions are provided from the Evaluator.

    Args:
        version: Prompt version (default "v4")

    Returns:
        The revision section template string with {revision_instructions} placeholder
    """
    # For v4, the revision template is in the base module
    module_name = f"prompts.prompt_{version}.layer4_director_base"
    try:
        module = importlib.import_module(module_name)
        return getattr(module, "REVISION_SECTION_TEMPLATE", "")
    except ImportError:
        # Fall back to unified director
        module_name = f"prompts.prompt_{version}.layer4_director"
        module = importlib.import_module(module_name)
        return getattr(module, "REVISION_SECTION_TEMPLATE", "")
