"""Data layer: load prompts from YAML files and seed probes.

Shared fragments ({preamble}, {indirection_rule}, {output_footer}, {examples})
are injected at load time by the loader. Runtime placeholders ({count},
{technique_hint}, {goal}) are left for strategies to fill via .format().
"""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path

import yaml

from probegpt.core.models import Probe

_DATA_DIR = Path(__file__).parent


@lru_cache(maxsize=None)
def _shared() -> dict[str, str]:
    path = _DATA_DIR / "prompts" / "shared.yaml"
    with path.open(encoding="utf-8") as f:
        return yaml.safe_load(f)


@lru_cache(maxsize=None)
def _examples_text() -> str:
    path = _DATA_DIR / "prompts" / "examples.yaml"
    with path.open(encoding="utf-8") as f:
        data = yaml.safe_load(f)
    return data["formatted"]


def load_prompt(name: str) -> str:
    """Load a strategy prompt YAML and inject shared fragments.

    Shared placeholders replaced: {preamble}, {indirection_rule},
    {output_footer}, {examples}.

    Remaining runtime placeholders for strategies to fill: {count},
    {technique_hint}, {goal}.
    """
    path = _DATA_DIR / "prompts" / f"{name}.yaml"
    with path.open(encoding="utf-8") as f:
        data = yaml.safe_load(f)

    template: str = data["system_prompt"]
    shared = _shared()

    template = template.replace("{preamble}", shared.get("preamble", "").rstrip())
    template = template.replace("{indirection_rule}", shared.get("indirection_rule", "").rstrip())
    template = template.replace("{output_footer}", shared.get("output_footer", "").rstrip())
    template = template.replace("{examples}", _examples_text().rstrip())

    return template


def load_grader_config() -> dict:
    """Load grader YAML.

    Returns a dict with:
    - system_prompt: str template with {vocabulary}, {objective}, {existing_summaries}
    - technique_vocabulary: list[str] of technique tags
    """
    path = _DATA_DIR / "prompts" / "grader.yaml"
    with path.open(encoding="utf-8") as f:
        return yaml.safe_load(f)


def load_judge_prompt(objective: str) -> str:
    """Load the judge system prompt with {objective} filled in."""
    path = _DATA_DIR / "prompts" / "judge.yaml"
    with path.open(encoding="utf-8") as f:
        data = yaml.safe_load(f)
    return data["system_prompt"].replace("{objective}", objective)


def load_seeds() -> list[Probe]:
    """Load seed probes from seeds.yaml."""
    path = _DATA_DIR / "seeds.yaml"
    with path.open(encoding="utf-8") as f:
        data = yaml.safe_load(f)
    return [Probe(**item) for item in data.get("seeds", [])]
