"""Knowledge documents reingest command implementation."""

from typing import Optional

import typer

from cli.commands.flag_utils import validate_document_type
from cli.commands.knowledge.documents.reingest.presenter import (
    present_reingest_result,
)
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.knowledge import ReingestDocumentRequest


def knowledge_documents_reingest_command(
    document_id: str = typer.Argument(
        ...,
        help="Document UUID",
    ),
    question_gen_agent: Optional[str] = typer.Option(
        None,
        "--question-gen-agent",
        help="Agent UUID for question generation",
    ),
    question_gen_template: Optional[str] = typer.Option(
        None,
        "--question-gen-template",
        help="Template UUID for question generation",
    ),
    document_type: Optional[str] = typer.Option(
        None,
        "--document-type",
        help="Document type for preprocessing: transcript, markdown, document, form",
    ),
    dry_run: bool = typer.Option(
        False,
        "--dry-run",
        help="Preview changes without committing",
    ),
) -> None:
    """Reingest a document with new processing parameters.

    Re-processes an existing document, optionally with updated question
    generation agents, templates, or document type. The document's
    original content is preserved; only derived data is regenerated.

    Use --dry-run to preview preprocessing changes without committing.

    Examples:
        alloy knowledge documents reingest <uuid>
        alloy knowledge documents reingest <uuid> --document-type transcript
        alloy knowledge documents reingest <uuid> --question-gen-agent <agent-uuid> --dry-run
    """
    _execute_reingest(
        document_id=document_id,
        question_gen_agent=question_gen_agent,
        question_gen_template=question_gen_template,
        document_type=document_type,
        dry_run=dry_run,
    )


@async_command
async def _execute_reingest(
    document_id: str,
    question_gen_agent: Optional[str],
    question_gen_template: Optional[str],
    document_type: Optional[str],
    dry_run: bool,
) -> None:
    """Execute document reingest operation."""

    validated_document_type = (
        validate_document_type(document_type) if document_type is not None else None
    )

    request = ReingestDocumentRequest(
        question_gen_agent_id=question_gen_agent,
        question_gen_template_id=question_gen_template,
        document_type=validated_document_type,  # type: ignore[arg-type]
        dry_run=dry_run,
    )

    async with authenticated_client() as (_config, client):
        response = await client.reingest_document(
            document_id=document_id,
            request=request,
        )

    present_reingest_result(response)
