"""Presenters for pipeline approval checkpoint command output."""

import json

from pydantic import BaseModel

from alloy_runtime_sdk.pipeline.types import ApprovalCheckpoint

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


class ApprovalDecisionData(BaseModel):
    decision_data: str


def _format_status(status: str) -> str:
    """Format approval status for display."""
    return status


def _format_approved(approved: bool | None) -> str:
    """Format approved boolean for display."""
    if approved is None:
        return "(pending)"
    return "Yes" if approved else "No"


def present_approval_checkpoint(checkpoint: ApprovalCheckpoint) -> None:
    """Present a single approval checkpoint with Rich formatting."""
    output = OutputService.get()

    fields = [
        FieldConfig("id", "Checkpoint ID", str),
        FieldConfig("pipeline_execution_id", "Execution ID", str),
        FieldConfig("approval_key", "Approval Key"),
        FieldConfig("status", "Status", _format_status),
        FieldConfig("approved", "Approved", _format_approved),
        FieldConfig(
            "decided_by_user_id", "Decided By", lambda v: format_optional(v, str)
        ),
        FieldConfig("decided_at", "Decided At", format_optional),
        FieldConfig("created_at", "Created At"),
    ]

    output.entity(
        checkpoint, f"Approval: {checkpoint.status}", fields, raw_payload=checkpoint
    )

    if checkpoint.decision_data:
        output.entity(
            ApprovalDecisionData(
                decision_data=json.dumps(checkpoint.decision_data, indent=2)
            ),
            "Approval Decision Data",
            [FieldConfig("decision_data", "Decision Data")],
        )


def present_approval_not_found(execution_id: str, approval_key: str) -> None:
    """Present a not-found message for an approval checkpoint."""
    output = OutputService.get()
    output.result(
        action="get",
        resource="approval_checkpoint",
        status="failed",
        identifier=execution_id,
        name=approval_key,
        extra_fields={
            "Reason": (
                f"No approval checkpoint found for execution {execution_id} "
                f"with key '{approval_key}'"
            )
        },
    )
