"""obol events - view agent event history."""
import re
from datetime import datetime, timedelta, timezone

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

_RELATIVE_RE = re.compile(r'^(\d+)([mhdw])$')
_RELATIVE_UNITS = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'}


def _parse_time(value):
    """Parse a time string into a UTC-aware datetime.

    Accepts relative durations (e.g. "30m", "2h", "1d", "1w") interpreted as
    that many units *before now*, or ISO 8601 datetime strings.
    """
    m = _RELATIVE_RE.match(value)
    if m:
        amount, unit = int(m.group(1)), m.group(2)
        delta = timedelta(**{_RELATIVE_UNITS[unit]: amount})
        return datetime.now(timezone.utc) - delta
    dt = datetime.fromisoformat(value)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt


@handle_api_error
def cmd_events(args):
    api = get_api()
    fmt = getattr(args, "format", "text")

    agent_id = getattr(args, "agent", None)
    action = getattr(args, "action", None)
    since = getattr(args, "since", None)
    until = getattr(args, "until", None)
    session = getattr(args, "session", None)
    limit = getattr(args, "limit", 50)

    # Build params for server-side search
    params = {"limit": limit}
    if agent_id:
        params["agent_id"] = agent_id
    if action:
        params["action"] = action
    if since:
        params["since"] = _parse_time(since).isoformat()
    if until:
        params["until"] = _parse_time(until).isoformat()
    if session:
        params["session_id"] = session

    data = api.search_events(**params)

    if fmt == "json":
        output(data, fmt="json")
        return

    events = data.get("events", [])
    if not events:
        print("No events found.")
        return

    print(f"Events: {len(events)} shown / {data.get('total', '?')} total")
    print()

    rows = []
    for e in events:
        rows.append([
            e.get("id", ""),
            e.get("agent_id", ""),
            e.get("action", "-"),
            (e.get("target", "") or "-")[:50],
            e.get("result", "-"),
            e.get("duration_ms", "-"),
            str(e.get("timestamp", "-"))[:19],
        ])

    table(
        ["ID", "Agent", "Action", "Target", "Result", "ms", "Timestamp"],
        rows,
        max_widths={3: 50, 6: 19},
    )



def setup_parser(subparsers):
    """Add events subparser."""
    parser = subparsers.add_parser("events", help="View events")
    parser.set_defaults(func=cmd_events)
    add_format_arg(parser)
    parser.add_argument("--agent", type=int, help="Filter by agent ID")
    parser.add_argument("--action", help="Filter by action type")
    parser.add_argument("--since", help="Show events after this time (ISO datetime or relative: 1h, 30m, 2d, 1w)")
    parser.add_argument("--until", help="Show events before this time (ISO datetime or relative: 1h, 30m, 2d, 1w)")
    parser.add_argument("--session", help="Filter by session ID (prefix match)")
    parser.add_argument("--limit", type=int, default=50, help="Max results")
