"""Knowledge synthesis update command implementation."""

from typing import Optional

import typer

from cli.commands.knowledge.synthesis.update.presenter import (
    present_synthesis_update_result,
)
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.file_content import resolve_content_or_raise
from alloy_runtime_types.dtos.knowledge import UpdateSynthesisRequest


def knowledge_synthesis_update_command(
    synthesis_id: str = typer.Argument(
        ...,
        help="Synthesis UUID",
    ),
    title: Optional[str] = typer.Option(
        None,
        "--title",
        help="New title for the synthesis",
    ),
    content: Optional[str] = typer.Option(
        None,
        "--content",
        help="New synthesis content (or @file)",
    ),
) -> None:
    """Update a synthesis document.

    Update synthesis properties like title or content.
    At least one of --title or --content must be provided.

    The --content flag accepts a text string or @file reference.

    Examples:
        alloy knowledge synthesis update <uuid> --title "New Title"
        alloy knowledge synthesis update <uuid> --content @updated.md
        alloy knowledge synthesis update <uuid> --title "New Title" --content "Updated content"
    """
    _execute_update(
        synthesis_id=synthesis_id,
        title=title,
        content_raw=content,
    )


@async_command
async def _execute_update(
    synthesis_id: str,
    title: Optional[str],
    content_raw: Optional[str],
) -> None:
    """Execute synthesis update operation."""

    resolved_content = resolve_content_or_raise(content_raw)

    if title is None and resolved_content is None:
        raise typer.BadParameter(
            "At least one of --title or --content must be provided"
        )

    request = UpdateSynthesisRequest(
        title=title,
        synthesis_content=resolved_content,
    )

    async with authenticated_client() as (_config, client):
        response = await client.update_synthesis(
            synthesis_id=synthesis_id,
            request=request,
        )

    present_synthesis_update_result(response)
