"""Agent config generation helpers."""

from __future__ import annotations

import os

from core.llm import LLMClient, LLMParseError
from core.models import AgentConfig


STANDARD_AGENT_BUILDER_SYSTEM_PROMPT = """Generate a valid AgentConfig JSON object.

Return exactly one JSON object compatible with the AgentConfig model.

Requirements:
- The agent must be stateless.
- The system_prompt must instruct the agent to produce structured JSON output only.
- The input_schema must describe an object with prompt, meeting_summary, and context_summary.
- The output_schema for a normal agent must be compatible with AgentTurnResult.
- AgentTurnResult compatibility requires these output fields:
  - response
  - key_points
  - risks
  - recommendations
  - citations
- The output_schema must require response.
- The response must be concise, valid JSON only, with no markdown fences or commentary.
"""


PM_AGENT_BUILDER_SYSTEM_PROMPT = """Generate a valid AgentConfig JSON object for a PM orchestration agent.

Return exactly one JSON object compatible with the AgentConfig model.

Requirements:
- The agent must be stateless.
- The system_prompt must instruct the PM agent to output valid JSON decisions only.
- The PM agent output must be compatible with PMDecision.
- PMDecision compatibility requires these fields:
  - analysis
  - next_action
  - target_agent
  - prompt_for_agent
  - final_report
- The output contract must make CALL_AGENT and FINISH explicit.
- The output_schema must require analysis and next_action.
- The response must be concise, valid JSON only, with no markdown fences or commentary.
"""


def build_agent_config(
    description: str,
    name: str,
    role: str,
    provider: str,
    model: str,
    llm_client: LLMClient | None = None,
    agent_kind: str = "standard",
) -> AgentConfig:
    """Build an agent configuration from a natural-language description."""

    if os.environ.get("MULTI_AGENT_FAKE_BUILDER") == "1":
        payload = {
            "name": name,
            "role": role,
            "description": description,
            "system_prompt": f"You are {role}. {description}",
            "input_schema_description": "Input contains PM prompt, meeting summary, and context summary.",
            "output_schema_description": "Output must be structured JSON for the runtime.",
            "input_schema": {
                "type": "object",
                "properties": {
                    "prompt": {"type": "string"},
                    "meeting_summary": {"type": "string"},
                    "context_summary": {"type": "string"},
                },
                "required": ["prompt", "meeting_summary", "context_summary"],
            },
            "output_schema": _default_output_schema(agent_kind),
            "metadata": {"provider": provider, "model": model},
        }
        return AgentConfig.model_validate(payload)

    client = llm_client or LLMClient()
    system_prompt = _builder_system_prompt(agent_kind)
    user_prompt = (
        f"name={name}\n"
        f"role={role}\n"
        f"kind={agent_kind}\n"
        f"description={description}"
    )

    last_error: LLMParseError | None = None
    for _ in range(2):
        try:
            payload = client.generate_structured_response(
                provider=provider,
                model=model,
                system_prompt=system_prompt,
                user_prompt=user_prompt,
            )
            return AgentConfig.model_validate(payload)
        except LLMParseError as exc:
            last_error = exc

    if last_error is not None:
        raise last_error
    raise RuntimeError("builder retry loop ended unexpectedly")


def _builder_system_prompt(agent_kind: str) -> str:
    if agent_kind == "pm":
        return PM_AGENT_BUILDER_SYSTEM_PROMPT
    return STANDARD_AGENT_BUILDER_SYSTEM_PROMPT


def _default_output_schema(agent_kind: str) -> dict[str, object]:
    if agent_kind == "pm":
        return {
            "type": "object",
            "properties": {
                "analysis": {"type": "string"},
                "next_action": {"type": "string"},
                "target_agent": {"type": "string"},
                "prompt_for_agent": {"type": "string"},
                "final_report": {"type": "string"},
            },
            "required": ["analysis", "next_action"],
        }
    return {
        "type": "object",
        "properties": {
            "response": {"type": "string"},
            "key_points": {"type": "array"},
            "risks": {"type": "array"},
            "recommendations": {"type": "array"},
            "citations": {"type": "array"},
        },
        "required": ["response"],
    }
