"""Presenter for pipeline execute command output."""

import json

from pydantic import BaseModel

from alloy_runtime_types.dtos.pipeline import ExecutePipelineResponse

from cli.infrastructure.formatting.fields import format_optional
from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.entity_renderer import FieldConfig


class ResultDataOutput(BaseModel):
    result_data: str


def _format_tags(response: ExecutePipelineResponse) -> str:
    """Format tags for display."""
    if not response.tags:
        return "(none)"
    return ", ".join(t.tag_path for t in response.tags)


def _format_duration(duration_ms: int | None) -> str:
    """Format duration for display."""
    if not duration_ms:
        return "-"
    return f"{duration_ms}ms"


def present_execution_result(response: ExecutePipelineResponse) -> None:
    """Present pipeline execution result."""
    output = OutputService.get()

    fields = [
        FieldConfig("execution_id", "Execution ID", str),
        FieldConfig("pipeline_id", "Pipeline ID", str),
        FieldConfig("status", "Status"),
        FieldConfig("external_id", "External ID", format_optional),
        FieldConfig("total_duration_ms", "Duration", _format_duration),
        FieldConfig("error_message", "Error", format_optional),
        FieldConfig("tags", "Tags", lambda _: _format_tags(response)),
    ]

    output.entity(
        response, f"Execution: {response.status}", fields, raw_payload=response
    )

    if response.result_data:
        output.entity(
            ResultDataOutput(result_data=json.dumps(response.result_data, indent=2)),
            "Execution Result Data",
            [FieldConfig("result_data", "Result Data")],
        )
