"""Generate system prompt from SaaSModel and write agent/prompt_generated.py."""

from pathlib import Path

from foremet.ingest.model import SaaSModel

TEMPLATE_PATH = Path(__file__).parent.parent / "templates" / "system_prompt.txt"


def _resources_and_actions_text(saas_model: SaaSModel) -> str:
    """Format resources and operations for the system prompt."""
    lines = []
    for op in saas_model.operations:
        summary = op.summary or op.description or f"{op.method} {op.path}"
        lines.append(f"- {op.method} {op.path}: {summary}")
    return "\n".join(lines) if lines else "No operations defined."


def generate_system_prompt(
    saas_model: SaaSModel,
    product_name: str,
    product_description: str | None = None,
) -> str:
    """Build system prompt string from SaaSModel and product info."""
    template = TEMPLATE_PATH.read_text()
    product_desc = product_description or (saas_model.description or "")
    if product_desc:
        product_desc = "\n" + product_desc
    resources_and_actions = _resources_and_actions_text(saas_model)
    return template.format(
        product_name=product_name,
        product_description=product_desc,
        resources_and_actions=resources_and_actions,
    )


def write_generated_prompt(
    output_dir: Path,
    saas_model: SaaSModel,
    product_name: str,
    product_description: str | None = None,
) -> Path:
    """Write agent/prompt_generated.py with SYSTEM_PROMPT constant."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    prompt = generate_system_prompt(saas_model, product_name, product_description)
    content = f"# Generated by foremet - do not edit by hand.\n\nSYSTEM_PROMPT = {repr(prompt)}\n"
    path = output_dir / "prompt_generated.py"
    path.write_text(content)
    return path
