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 monitor_impl(
    *,
    config_dir: Path,
    agent: str = "",
    event_type: str = "",
    limit: int = 100,
) -> None:
    items = armorer_db.list_runtime_events(
        config_dir,
        limit=limit,
        agent=agent,
        event_type=event_type,
    )
    if not items:
        cli_common.console.print("[dim]No runtime events matched the current filters.[/dim]")
        return
    table = Table(title="Runtime Events")
    table.add_column("Time", style="cyan")
    table.add_column("Agent", style="magenta")
    table.add_column("Type", style="yellow")
    table.add_column("Severity")
    table.add_column("Verdict")
    table.add_column("Target")
    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 "-"
        target = str(item.get("dst_host") or item.get("dst_ip") or item.get("path") or "-")
        table.add_row(
            when,
            str(item.get("agent_alias") or "-"),
            str(item.get("event_type") or "-"),
            str(item.get("severity") or "-"),
            str(item.get("verdict") or "-"),
            target,
        )
    cli_common.console.print(table)
