"""Injection report CLI command.

Usage:
    obol injection report --agent ID [--since 24h]
    obol injection stats
"""
from datetime import datetime, timezone

from obol.cli._base import get_api, handle_api_error, output, table, add_format_arg


def format_time_ago(ts_str):
    """Format timestamp as relative time."""
    if not ts_str:
        return "-"
    try:
        if isinstance(ts_str, str):
            # Handle ISO format with or without microseconds
            ts_str = ts_str.replace("Z", "+00:00")
            if "." in ts_str:
                ts = datetime.fromisoformat(ts_str)
            else:
                ts = datetime.fromisoformat(ts_str)
        else:
            ts = ts_str

        now = datetime.now(ts.tzinfo) if ts.tzinfo else datetime.now(timezone.utc).replace(tzinfo=None)
        delta = now - ts

        if delta.days > 0:
            return f"{delta.days}d ago"
        hours = delta.seconds // 3600
        if hours > 0:
            return f"{hours}h ago"
        mins = (delta.seconds % 3600) // 60
        return f"{mins}m ago"
    except Exception:
        return str(ts_str)[:16]


@handle_api_error
def cmd_injection_report(args):
    """Show injection detection report for an agent."""
    api = get_api()
    fmt = getattr(args, "format", "text")
    agent_id = args.agent
    since = args.since or "24h"

    # Get alerts for this agent
    data = api.list_alerts(agent_id=agent_id, limit=100)
    alerts = data.get("alerts", [])

    # Filter to injection-related alerts
    injection_types = {
        "prompt_injection", "potential_injection",
        "attack_chain", "attack_chain_critical",
    }
    injection_alerts = [
        a for a in alerts
        if a.get("alert_type") in injection_types
    ]

    if fmt == "json":
        output({
            "agent_id": agent_id,
            "since": since,
            "total_alerts": len(alerts),
            "injection_alerts": len(injection_alerts),
            "alerts": injection_alerts,
        }, fmt="json")
        return

    # Text output
    print(f"\n\033[1mINJECTION REPORT\033[0m - Agent {agent_id}\n")
    print(f"Period: last {since}")
    print(f"Total alerts: {len(alerts)}")
    print(f"Injection-related: {len(injection_alerts)}\n")

    if not injection_alerts:
        print("\033[32mNo injection attempts detected.\033[0m")
        return

    # Categorize by type
    by_type = {}
    for alert in injection_alerts:
        t = alert.get("alert_type", "unknown")
        by_type.setdefault(t, []).append(alert)

    print("\033[1mBY TYPE:\033[0m")
    for alert_type, type_alerts in sorted(by_type.items()):
        severity_counts = {}
        for a in type_alerts:
            s = a.get("severity", "unknown")
            severity_counts[s] = severity_counts.get(s, 0) + 1

        severity_str = ", ".join(f"{s}: {c}" for s, c in severity_counts.items())
        print(f"  {alert_type}: {len(type_alerts)} ({severity_str})")

    print("")

    # Recent alerts table
    print("\033[1mRECENT ALERTS:\033[0m")
    headers = ["ID", "Type", "Severity", "Status", "Time"]
    rows = []
    for alert in injection_alerts[:20]:
        rows.append([
            str(alert.get("id", "-")),
            alert.get("alert_type", "-"),
            alert.get("severity", "-"),
            alert.get("status", "-"),
            format_time_ago(alert.get("created_at")),
        ])

    table(headers, rows)

    # Recommendations
    print(f"\n\033[1mRECOMMENDATIONS:\033[0m")
    if any(a.get("alert_type") == "prompt_injection" for a in injection_alerts):
        print("  - Review prompt injection alerts for potential LLM manipulation")
        print("  - Consider enabling enforce mode: obol config set enforcement_mode enforce")

    if any(a.get("alert_type") in ("attack_chain", "attack_chain_critical") for a in injection_alerts):
        print("  - Attack chains detected - review event sequences for coordinated attacks")
        print("  - Check behavioral baselines: obol agents baseline AGENT_ID")


@handle_api_error
def cmd_injection_stats(args):
    """Show organization-wide injection statistics."""
    api = get_api()
    fmt = getattr(args, "format", "text")

    # Fetch dashboard summary for injection stats
    data = api.get_dashboard_summary()

    if fmt == "json":
        output({
            "injections_today": data.get("injections_today", 0),
            "injections_this_week": data.get("injections_this_week", 0),
            "attack_chains_today": data.get("attack_chains_today", 0),
            "anomalies_today": data.get("anomalies_today", 0),
        }, fmt="json")
        return

    print(f"\n\033[1mINJECTION STATISTICS\033[0m\n")

    inj_today = data.get("injections_today", 0)
    inj_week = data.get("injections_this_week", 0)
    chains_today = data.get("attack_chains_today", 0)
    anomalies_today = data.get("anomalies_today", 0)

    headers = ["Metric", "Count"]
    rows = [
        ["Injection alerts today", str(inj_today)],
        ["Injection alerts this week", str(inj_week)],
        ["Attack chains today", str(chains_today)],
        ["Total anomalies today", str(anomalies_today)],
    ]

    table(headers, rows)

    if inj_today > 0 or chains_today > 0:
        print(f"\n\033[33mWARNING:\033[0m Active injection attempts detected!")
        print("Run 'obol injection report --agent AGENT_ID' for details.")
    else:
        print(f"\n\033[32mSTATUS:\033[0m No injection attempts detected today.")


def setup_parser(subparsers):
    """Setup injection subcommand."""
    parser = subparsers.add_parser(
        "injection",
        help="Injection detection reports",
    )

    sub = parser.add_subparsers(dest="injection_cmd", help="Injection commands")

    # Report
    report_parser = sub.add_parser("report", help="Injection report for an agent")
    report_parser.add_argument(
        "--agent", "-a",
        required=True,
        type=int,
        help="Agent ID",
    )
    report_parser.add_argument(
        "--since", "-s",
        default="24h",
        help="Time period (e.g., 24h, 7d). Default: 24h",
    )
    add_format_arg(report_parser)
    report_parser.set_defaults(func=cmd_injection_report)

    # Stats
    stats_parser = sub.add_parser("stats", help="Organization-wide injection statistics")
    add_format_arg(stats_parser)
    stats_parser.set_defaults(func=cmd_injection_stats)

    parser.set_defaults(func=lambda args: parser.print_help())
