"""Shared UI error rendering helpers."""

from __future__ import annotations

from nicegui import ui

from transcription.errors import AppError
from transcription.errors import ErrorCategory
from transcription.errors import classify_unexpected_error


def to_app_error(exc: Exception, *, operation: str) -> AppError:
    """Normalize any exception for consistent UI display."""
    if isinstance(exc, AppError):
        return exc
    return classify_unexpected_error(exc, operation=operation)


def show_error(exc: Exception, *, title: str, operation: str) -> None:
    """Display a visible, actionable UI error with trace id."""
    error = to_app_error(exc, operation=operation)
    ui.notify(
        f"{title}: {error.message} (ref: {error.error_id})",
        type="negative",
        timeout=0,
        close_button="Dismiss",
    )

    with ui.card().classes("vibe-card--error q-mt-md q-pa-md"):
        ui.label(title).classes("text-subtitle1")
        ui.label(error.message)
        ui.label(f"Suggested action: {error.suggestion}").classes("text-weight-medium")
        ui.label(f"Error reference: {error.error_id}").classes("text-caption")
        ui.label(f"Category: {error.category.value}").classes("text-caption")


def summarize_error(exc: Exception, *, operation: str) -> str:
    """Return short one-line summary for status labels."""
    error = to_app_error(exc, operation=operation)
    if error.category == ErrorCategory.INTERNAL_UNEXPECTED:
        return f"Unexpected error (ref: {error.error_id})"
    return f"{error.message} (ref: {error.error_id})"
