from __future__ import annotations

from datetime import datetime
from pathlib import Path

from rich.table import Table

from armorer import db as armorer_db
from armorer.cli import common as cli_common


def alerts_impl(
    *,
    config_dir: Path,
    sort: str = "criticality",
    status: str = "",
    agent: str = "",
    limit: int = 50,
) -> None:
    items = armorer_db.list_security_alerts(
        config_dir,
        limit=limit,
        sort=sort,
        status=status,
        agent=agent,
    )
    table = Table(title="Armorer Alerts", show_lines=False)
    table.add_column("Time", style="cyan")
    table.add_column("Sev", style="bold")
    table.add_column("Agent", style="magenta")
    table.add_column("Flags", style="yellow")
    table.add_column("Source", style="green")
    table.add_column("Conf", justify="right")
    table.add_column("Status")
    if not items:
        cli_common.console.print("[dim]No alerts matched the current filters.[/dim]")
        return
    for item in items:
        ts = float(item.get("ts") or 0.0)
        when = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-"
        flags = ", ".join(item.get("flags") or []) or "-"
        table.add_row(
            when,
            str(item.get("severity") or "-"),
            str(item.get("agent") or "-"),
            flags,
            str(item.get("source_family") or item.get("source") or "-"),
            f"{float(item.get('confidence') or 0.0):.2f}",
            str(item.get("status") or "-"),
        )
    cli_common.console.print(table)
