"""
Prompt loader utility for loading agent prompts from TOML files.
"""

import sys
from pathlib import Path
from typing import Optional

if sys.version_info >= (3, 11):
    import tomllib
else:
    try:
        import tomli as tomllib  # type: ignore
    except ImportError as e:
        raise ImportError("tomli package required for Python < 3.11. Install with: pip install tomli") from e


def load_prompt(processor_name: str, prompt_key: str, prompts_dir: Optional[Path] = None) -> str:
    """
    Load a specific prompt from a processor's TOML file.

    Args:
        processor_name: Name of the processor (e.g., 'table_inference')
        prompt_key: Key of the prompt to load (e.g., 'system')
        prompts_dir: Optional directory containing prompts (defaults to this package directory)

    Returns:
        The prompt content as a string

    Raises:
        FileNotFoundError: If the TOML file does not exist
        KeyError: If the prompt key is not found in the TOML file
        ValueError: If the prompt content is empty

    Example:
        >>> system_prompt = load_prompt("table_inference", "system")
    """
    if prompts_dir is None:
        prompts_dir = Path(__file__).parent

    toml_file = prompts_dir / f"{processor_name}.toml"

    if not toml_file.exists():
        raise FileNotFoundError(f"Prompt file not found: {toml_file}")

    with open(toml_file, "rb") as f:
        data = tomllib.load(f)

    try:
        # Access prompts.{prompt_key}.text
        prompt_data = data["prompts"][prompt_key]
        content = prompt_data["text"].strip()
    except KeyError as e:
        available_keys = list(data.get("prompts", {}).keys())
        raise KeyError(
            f"Prompt key '{prompt_key}' not found in {toml_file}. Available keys: {available_keys}"
        ) from e

    if not content:
        raise ValueError(f"Prompt content is empty for key '{prompt_key}' in {toml_file}")

    return content
