"""Knowledge synthesis create command implementation."""

from typing import Annotated, Optional
from uuid import UUID

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.knowledge.synthesis.create.presenter import (
    present_synthesis_create_success,
)
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.kv_parser import parse_kv_pairs
from alloy_runtime_types.dtos.knowledge import CreateSynthesisRequest


def knowledge_synthesis_create_command(
    topic: str = typer.Option(
        ...,
        "-t",
        "--topic",
        help="Topic to research and synthesize",
    ),
    collections: str = typer.Option(
        ...,
        "-C",
        "--collections",
        help="Comma-separated collection UUIDs to include",
    ),
    agent: str = typer.Option(
        ...,
        "-a",
        "--agent",
        help="Synthesizer agent UUID (must have rag_search tool)",
    ),
    template: str = typer.Option(
        ...,
        "-T",
        "--template",
        help="Synthesis template UUID (receives {{ topic }} variable)",
    ),
    title: Optional[str] = typer.Option(
        None,
        "--title",
        help="Title for the synthesis (defaults to topic)",
    ),
    metadata: Annotated[
        Optional[list[str]],
        typer.Option(
            "-m",
            "--metadata",
            help="Metadata (key=value or key:=json). Repeatable.",
        ),
    ] = None,
) -> None:
    """Create a corpus-level synthesis.

    A synthesis uses an agent with RAG tools to research a topic across
    specified collections and generate a comprehensive response. The
    synthesis is accepted asynchronously, and identical payloads reuse the
    existing synthesis. Poll the synthesis status
    to check for completion.

    Examples:
        alloy knowledge synthesis create -t "API authentication methods" \\
            -C <collection-uuid> -a <agent-uuid> -T <template-uuid>

        alloy knowledge synthesis create -t "Product roadmap summary" \\
            -C <col1>,<col2> -a <agent> -T <template> --title "Q1 Roadmap"

        alloy knowledge synthesis create -t "Security best practices" \\
            -C <collection> -a <agent> -T <template> -m priority=high
    """
    _execute_create_from_flags(
        topic=topic,
        collections=collections,
        agent=agent,
        template=template,
        title=title,
        metadata=metadata,
    )


def _execute_create_from_flags(
    topic: str,
    collections: str,
    agent: str,
    template: str,
    title: Optional[str],
    metadata: Optional[list[str]],
) -> None:
    """Build and execute synthesis creation from command flags."""
    # Parse collection IDs
    collection_ids: list[UUID] = []
    for cid in collections.split(","):
        cid = cid.strip()
        if cid:
            collection_ids.append(validate_uuid(cid, "collection"))

    if not collection_ids:
        raise typer.BadParameter("At least one collection UUID is required")

    # Validate agent and template UUIDs
    agent_id = validate_uuid(agent, "agent")
    template_id = validate_uuid(template, "template")

    # Parse metadata (httpie style)
    parsed_metadata = parse_kv_pairs(metadata) if metadata else None

    request = CreateSynthesisRequest(
        topic=topic,
        collection_ids=collection_ids,
        synthesizer_agent_id=agent_id,
        synthesis_template_id=template_id,
        title=title,
        metadata=parsed_metadata,
    )

    _execute_create(request)


@async_command
async def _execute_create(request: CreateSynthesisRequest) -> None:
    """Execute the synthesis creation with the given request."""
    async with authenticated_client() as (_config, client):
        response = await client.create_synthesis(request)

    present_synthesis_create_success(response)
