"""obol fp - mark an alert as false positive.

    obol fp <alert-id>                Mark alert as false positive
    obol fp <alert-id> --note "why"   With explanation
    obol fp <alert-id> --allow        Also create allowlist rule
"""
import sys

from obol.cli._base import get_api, error


def cmd_fp(args):
    alert_id = getattr(args, "alert_id", None)
    if not alert_id:
        print("Usage: obol fp <alert-id> [--note 'reason'] [--allow]")
        return

    note = getattr(args, "note", "") or ""

    api = get_api()

    # Resolve alert as false_positive
    try:
        result = api.request(
            "POST", f"/alerts/{alert_id}/resolve",
            json={"status": "false_positive", "note": note},
        )
        print(f"Alert {alert_id} marked as false positive.")

        # Show trust score restoration info
        if isinstance(result, dict):
            agent_id = result.get("agent_id")
            if agent_id:
                print(f"Trust score for agent {agent_id} will be fully restored.")

    except Exception as e:
        error(f"Failed to resolve alert: {e}")

    # Optionally create allowlist rule
    if getattr(args, "allow", False):
        try:
            from obol.hooks.allowlist import add_rule

            # Try to extract flag info from the alert
            try:
                alert = api.request("GET", f"/alerts/{alert_id}")
                flag = None
                if isinstance(alert, dict):
                    flags = alert.get("flags") or alert.get("detected_patterns") or []
                    if isinstance(flags, list) and flags:
                        flag = flags[0]
                    elif isinstance(flags, str):
                        flag = flags
                if flag:
                    rule_id = add_rule(
                        flag,
                        note=f"FP from alert {alert_id}" + (f": {note}" if note else ""),
                    )
                    print(f"Allowlist rule created: {rule_id} for flag '{flag}'")
                else:
                    print("Could not extract flag from alert to create allowlist rule.")
            except Exception:
                print("Could not fetch alert details for allowlist rule.")
        except ImportError:
            print("Allowlist module not available.")


def setup_parser(subparsers):
    parser = subparsers.add_parser("fp", help="Mark alert as false positive")
    parser.add_argument("alert_id", nargs="?", help="Alert ID to mark as FP")
    parser.add_argument("--note", "-n", help="Explanation for the FP")
    parser.add_argument("--allow", action="store_true",
                        help="Also create allowlist rule from this alert")
    parser.set_defaults(func=cmd_fp)
