"""Presenter for credentials list command output."""

from datetime import UTC, datetime

from pydantic import BaseModel

from alloy_runtime_types.dtos.credential_list import ListOrganizationCredentialsResponse

from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.list_renderer import ColumnConfig


def _format_date(value: datetime | None) -> str:
    if value is None:
        return "(null)"
    return value.astimezone(UTC).date().isoformat()


def _format_state(item: object) -> str:
    credential = getattr(item, "is_active", None)
    expires_at = getattr(item, "expires_at", None)

    if credential is False:
        return "Inactive"
    if isinstance(expires_at, datetime) and expires_at <= datetime.now(UTC):
        return "Expired"
    return "Active"


def _format_provider_or_tool(value: object) -> str:
    if value is None:
        return "-"
    if hasattr(value, "value"):
        return str(getattr(value, "value"))
    return str(value)


class CredentialListRow(BaseModel):
    name: str
    id: str
    type: str
    provider_or_tool: str
    created: str
    expires: str
    state: str


def present_credentials_list(response: ListOrganizationCredentialsResponse) -> None:
    output = OutputService.get()

    rows = [
        CredentialListRow(
            name=credential.name,
            id=str(credential.id),
            type=credential.type,
            provider_or_tool=_format_provider_or_tool(
                credential.service_key or credential.provider_key
            ),
            created=_format_date(credential.created_at),
            expires=_format_date(credential.expires_at),
            state=_format_state(credential),
        )
        for credential in response.credentials
    ]

    columns = [
        ColumnConfig(source_field="name", header_label="Name"),
        ColumnConfig(source_field="id", header_label="ID"),
        ColumnConfig(source_field="type", header_label="Type"),
        ColumnConfig(source_field="provider_or_tool", header_label="Provider/Tool"),
        ColumnConfig(source_field="created", header_label="Created"),
        ColumnConfig(source_field="expires", header_label="Expires"),
        ColumnConfig(source_field="state", header_label="State"),
    ]

    row_models: list[BaseModel] = [row for row in rows]

    output.table(
        items=row_models,
        title="Credentials",
        columns=columns,
        raw_payload=response,
    )
