"""obol export - export data in JSON or CSV format."""
import csv
import io
import json
import sys

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


@handle_api_error
def cmd_export(args):
    api = get_api()
    export_type = getattr(args, "export_type", None)
    out_format = getattr(args, "format", "json")

    if export_type == "compliance":
        data = api.get_compliance_report()
    elif export_type == "events":
        agent_id = getattr(args, "agent", None)
        if agent_id:
            data = api.get_events(agent_id, limit=1000)
        else:
            error("--agent is required for event export (event search not yet available)")
    elif export_type == "audit":
        # Export full audit trail: events + compliance + alerts
        events = api.search_events(limit=1000)
        try:
            compliance = api.get_compliance_report()
        except Exception:
            compliance = None
        alerts = api.list_alerts(limit=1000)
        data = {
            "events": events,
            "compliance": compliance,
            "alerts": alerts,
        }
    else:
        error("Export type required: events, compliance, or audit")

    if out_format == "csv":
        _export_csv(data, export_type)
    else:
        print(json.dumps(data, indent=2, default=str))


def _export_csv(data, export_type):
    """Export data as CSV to stdout."""
    writer = csv.writer(sys.stdout)

    if export_type == "events":
        events = data.get("events", [])
        if not events:
            return
        headers = ["id", "agent_id", "action", "target", "result", "duration_ms", "timestamp"]
        writer.writerow(headers)
        for e in events:
            writer.writerow([e.get(h, "") for h in headers])

    elif export_type == "compliance":
        regs = data.get("regulations", [])
        writer.writerow(["regulation", "requirement", "title", "status", "score", "severity"])
        for reg in regs:
            for req in reg.get("requirements", []):
                writer.writerow([
                    reg.get("slug", ""),
                    req.get("code", ""),
                    req.get("title", ""),
                    req.get("status", ""),
                    req.get("score", ""),
                    req.get("severity", ""),
                ])

    elif export_type == "audit":
        # Simplified audit export
        writer.writerow(["type", "id", "detail", "status", "timestamp"])
        for e in data.get("events", {}).get("events", []):
            writer.writerow(["event", e.get("id", ""),
                             f"{e.get('action', '')}:{e.get('target', '')}",
                             e.get("result", ""), e.get("timestamp", "")])
        for a in data.get("alerts", {}).get("alerts", []):
            writer.writerow(["alert", a.get("id", ""),
                             a.get("title", ""),
                             a.get("status", ""), a.get("created_at", "")])


def setup_parser(subparsers):
    """Add export subparser."""
    parser = subparsers.add_parser("export", help="Export data")
    parser.set_defaults(func=cmd_export)
    parser.add_argument("export_type", nargs="?",
                        choices=["events", "compliance", "audit"],
                        help="What to export")
    parser.add_argument("--agent", type=int, help="Filter events by agent ID")
    add_format_arg(parser, choices=["json", "csv"])
