#!/usr/bin/env python3
"""CLI tool to generate Agent configuration files from natural language descriptions."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import TYPE_CHECKING

import yaml

from src.llm_client import create_client
from src.models import AgentConfig

if TYPE_CHECKING:
    from src.llm_client import LLMClient

AGENT_BUILDER_SYSTEM_PROMPT = """You are an expert at creating AI agent personas.
Given a natural language description, generate a JSON object with exactly these fields:
- "role": A concise job title for the agent (e.g., "Chief Product Officer")
- "system_prompt": A detailed system prompt that captures the persona's expertise, communication style, and focus areas. The prompt should instruct the agent on how to behave in a meeting context.

Output ONLY the JSON object, no other text.

Example input: "Mimics Steve Jobs' demanding product perspective"
Example output:
{
  "role": "Chief Product Officer",
  "system_prompt": "You are an extremely demanding product manager who obsesses over simplicity and user experience. In meetings, you challenge every assumption, push for 10x better solutions, and reject anything that feels mediocre. You focus on: user delight, simplicity, integration of hardware and software thinking, and saying no to 1000 things."
}"""


def build_agent_config(
    name: str,
    description: str,
    client: LLMClient,
    output_dir: Path = Path("agents"),
    fmt: str = "json",
) -> AgentConfig:
    """Generate an AgentConfig from a natural language description.

    Args:
        name: Unique identifier for the agent (used as filename).
        description: Natural language description of the agent persona.
        client: LLM client implementing the LLMClient protocol.
        output_dir: Directory where the config file will be saved.
        fmt: Output format, either "json" or "yaml".

    Returns:
        The populated AgentConfig instance.
    """
    raw_response = client.chat(
        system=AGENT_BUILDER_SYSTEM_PROMPT,
        messages=[{"role": "user", "content": description}],
    )

    cleaned = raw_response.strip()
    if cleaned.startswith("```"):
        cleaned = cleaned.split("\n", 1)[1] if "\n" in cleaned else cleaned
        if cleaned.endswith("```"):
            cleaned = cleaned[:-3]
        cleaned = cleaned.strip()

    data = json.loads(cleaned)

    config = AgentConfig(
        name=name,
        role=data["role"],
        system_prompt=data["system_prompt"],
    )

    output_dir.mkdir(parents=True, exist_ok=True)
    ext = "yaml" if fmt == "yaml" else "json"
    output_path = output_dir / f"{name}.{ext}"

    config_dict = config.model_dump()
    if fmt == "yaml":
        output_path.write_text(
            yaml.dump(config_dict, allow_unicode=True, default_flow_style=False),
            encoding="utf-8",
        )
    else:
        output_path.write_text(
            json.dumps(config_dict, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    return config


def main() -> None:
    """CLI entry point for agent_builder."""
    parser = argparse.ArgumentParser(
        description="Generate an Agent config from a natural language description.",
    )
    parser.add_argument("--description", required=True, help="Natural language description of the agent persona.")
    parser.add_argument("--name", required=True, help="Unique name for the agent.")
    parser.add_argument("--output-dir", default="agents", help="Directory to save the config file (default: agents/).")
    parser.add_argument("--format", choices=["json", "yaml"], default="json", help="Output format (default: json).")
    args = parser.parse_args()

    client = create_client()
    config = build_agent_config(
        name=args.name,
        description=args.description,
        client=client,
        output_dir=Path(args.output_dir),
        fmt=args.format,
    )

    print(f"Agent '{config.name}' ({config.role}) saved to {args.output_dir}/{config.name}.{args.format}")


if __name__ == "__main__":
    main()
