"""``ilum history`` command."""

from __future__ import annotations

import typer

from ilum.cli.defaults import resolve_profile_defaults
from ilum.config.paths import IlumPaths
from ilum.core.audit import AuditLog


def history(
    release: str | None = typer.Option(
        None, "--release", "-r", show_default="from profile", help="Filter by release."
    ),
    namespace: str | None = typer.Option(
        None, "--namespace", "-n", show_default="from profile", help="Kubernetes namespace."
    ),
    context: str | None = typer.Option(
        None, "--context", show_default="from profile", help="Kubernetes context."
    ),
    last: int | None = typer.Option(None, "--last", help="Show only the last N entries."),
    operation: str | None = typer.Option(
        None,
        "--operation",
        help="Filter by operation type (install, upgrade, enable, disable, uninstall).",
    ),
) -> None:
    """Show operation history for Ilum releases."""
    release, namespace, context = resolve_profile_defaults(release, namespace, context)
    import ilum.cli.output as output_mod

    console = output_mod.console

    paths = IlumPaths.default()
    paths.ensure_dirs()
    audit_log = AuditLog(paths.state_dir)

    entries = audit_log.query(
        release=release if release != "ilum" else None,
        last_n=last,
        operation=operation,
    )

    if not entries:
        console.info("No history entries found.")
        return

    from ilum.cli.formatters import CommandResult, OutputFormat, ResultFormatter

    fmt = OutputFormat(console.output_format)

    if fmt != OutputFormat.TABLE:
        from dataclasses import asdict

        result = CommandResult(
            data=[asdict(e) for e in entries],
            summary=f"{len(entries)} entries",
        )
        ResultFormatter().format(result, fmt, console)
        return

    # Table output
    rows: list[list[str]] = []
    for entry in entries:
        duration = f"{entry.duration_seconds:.1f}s" if entry.duration_seconds else "-"
        modules_str = ", ".join(entry.modules[:3])
        if len(entry.modules) > 3:
            modules_str += f" (+{len(entry.modules) - 3})"
        status = "[green]OK[/green]" if entry.success else f"[red]FAIL[/red] {entry.error_code}"
        rows.append(
            [
                entry.timestamp[:19],  # Trim microseconds
                entry.operation,
                entry.release,
                entry.chart_version or "-",
                modules_str or "-",
                duration,
                status,
            ]
        )

    console.table(
        "Operation History",
        ["Timestamp", "Operation", "Release", "Version", "Modules", "Duration", "Status"],
        rows,
    )
