"""Pipeline execution get command implementation."""

import json
from pathlib import Path
from uuid import UUID

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.executions.presenter import present_execution_detail
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.output import OutputService


def pipelines_executions_get_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    execution_id: str = typer.Argument(
        ...,
        help="Execution UUID",
    ),
    print_logs: bool = typer.Option(
        False,
        "--print-logs",
        help="Print execution logs",
    ),
    result_json_file: str | None = typer.Option(
        None,
        "--result-json-file",
        help="Write execution result to JSON file",
    ),
) -> None:
    """Get details of a pipeline execution.

    Examples:
        alloy pipelines executions get 123e4567... 456e7890...
    """
    p_uuid = validate_uuid(pipeline_id, "pipeline")
    e_uuid = validate_uuid(execution_id, "execution")
    _execute_get(
        pipeline_id=p_uuid,
        execution_id=e_uuid,
        print_logs=print_logs,
        result_json_file=result_json_file,
    )


@async_command
async def _execute_get(
    pipeline_id: UUID,
    execution_id: UUID,
    print_logs: bool,
    result_json_file: str | None,
) -> None:
    """Execute get execution operation."""
    async with authenticated_client() as (_config, client):
        response = await client.get_pipeline_execution(pipeline_id, execution_id)

    if result_json_file is not None:
        _write_result_json_file(response.execution.result_data, result_json_file)

    present_execution_detail(response, print_logs=print_logs)


def _write_result_json_file(
    result_data: dict[str, object] | None, output_file: str
) -> None:
    file_path = Path(output_file).expanduser().resolve()
    file_path.parent.mkdir(parents=True, exist_ok=True)
    file_path.write_text(json.dumps(result_data, indent=2), encoding="utf-8")
    OutputService.get().result(
        action="write",
        resource="pipeline_execution_result",
        extra_fields={"Path": str(file_path)},
    )
