"""Generate DataAgent, DomainAgent, and CoordinatorAgent code from ASD definitions."""

from __future__ import annotations

from pathlib import Path

from ninja_core.schema.domain import DomainSchema
from ninja_core.schema.entity import EntitySchema

from .base import get_template_env, write_generated_file


def generate_data_agent(entity: EntitySchema, output_dir: Path) -> Path:
    """Generate a DataAgent file for a single entity.

    Args:
        entity: The entity schema to generate from.
        output_dir: Directory to write the generated file into.

    Returns:
        Path to the generated file.
    """
    env = get_template_env()
    template = env.get_template("data_agent.py.j2")
    content = template.render(entity=entity)

    file_path = output_dir / f"{entity.name.lower()}_agent.py"
    write_generated_file(file_path, content)
    return file_path


def generate_domain_agent(domain: DomainSchema, output_dir: Path) -> Path:
    """Generate a DomainAgent file for a single domain.

    Args:
        domain: The domain schema to generate from.
        output_dir: Directory to write the generated file into.

    Returns:
        Path to the generated file.
    """
    env = get_template_env()
    template = env.get_template("domain_agent.py.j2")
    content = template.render(domain=domain)

    file_path = output_dir / f"{domain.name.lower()}_agent.py"
    write_generated_file(file_path, content)
    return file_path


def generate_coordinator(domains: list[DomainSchema], output_dir: Path) -> Path:
    """Generate a CoordinatorAgent file wiring all domain agents.

    Args:
        domains: List of domain schemas to wire together.
        output_dir: Directory to write the generated file into.

    Returns:
        Path to the generated file.
    """
    env = get_template_env()
    template = env.get_template("coordinator_agent.py.j2")
    domain_names = [d.name for d in domains]
    content = template.render(domains=domains, domain_names=domain_names)

    file_path = output_dir / "coordinator_agent.py"
    write_generated_file(file_path, content)
    return file_path


def generate_agents(
    entities: list[EntitySchema],
    domains: list[DomainSchema],
    output_dir: Path,
) -> list[Path]:
    """Generate all agent files (data + domain + coordinator).

    Args:
        entities: List of entity schemas.
        domains: List of domain schemas.
        output_dir: Base directory for generated agent files.

    Returns:
        List of paths to generated files.
    """
    agents_dir = output_dir / "_generated" / "agents"
    paths: list[Path] = []

    # Generate data agents
    init_lines = [
        "# AUTO-GENERATED by ninja-codegen — DO NOT EDIT",
        "",
    ]

    for entity in entities:
        path = generate_data_agent(entity, agents_dir)
        paths.append(path)
        init_lines.append(
            f"from .{entity.name.lower()}_agent import {entity.name.upper()}_ENTITY, {entity.name.lower()}_data_agent"
        )

    # Generate domain agents
    for domain in domains:
        path = generate_domain_agent(domain, agents_dir)
        paths.append(path)
        init_lines.append(
            f"from .{domain.name.lower()}_agent import {domain.name.upper()}_DOMAIN"
            f", create_{domain.name.lower()}_domain_agent"
        )

    # Generate coordinator agent
    if domains:
        path = generate_coordinator(domains, agents_dir)
        paths.append(path)
        init_lines.append("from .coordinator_agent import create_coordinator")

    if entities or domains:
        init_lines.append("")

    init_path = agents_dir / "__init__.py"
    write_generated_file(init_path, "\n".join(init_lines))
    paths.append(init_path)

    return paths
