"""obol allow - manage local detection allowlist.

    obol allow <flag>                          Suppress a flag
    obol allow <flag> --tool Bash              Only for Bash tool
    obol allow <flag> --target-contains docker Only when target contains "docker"
    obol allow <flag> --note "reason"          With explanation
    obol allow <flag> --expires 30             Auto-expire in 30 days
    obol allow list                            Show all rules
    obol allow remove <rule-id>                Remove a rule
"""
import sys
import time


def cmd_allow(args):
    action = getattr(args, "flag_or_action", None)
    if not action:
        print("Usage: obol allow <flag> [options]")
        print("       obol allow list")
        print("       obol allow remove <rule-id>")
        return

    # ── List rules ──
    if action == "list":
        try:
            from obol.hooks.allowlist import list_rules
        except ImportError:
            print("Allowlist module not available.")
            return

        rules = list_rules()
        if not rules:
            print("No allowlist rules configured.")
            print("Add one: obol allow <flag_name>")
            return

        print(f"Allowlist rules ({len(rules)}):\n")
        for rule in rules:
            rid = rule.get("id", "?")
            flag = rule.get("flag", "?")
            tool = rule.get("tool", "any")
            target = rule.get("target_contains", "any")
            note = rule.get("note", "")
            created = rule.get("created_at", 0)
            expires = rule.get("expires_at")

            created_str = time.strftime("%Y-%m-%d", time.localtime(created)) if created else "?"
            exp_str = ""
            if expires:
                remaining = expires - time.time()
                if remaining > 86400:
                    exp_str = f" (expires in {int(remaining / 86400)}d)"
                elif remaining > 3600:
                    exp_str = f" (expires in {int(remaining / 3600)}h)"
                elif remaining > 0:
                    exp_str = f" (expires in {int(remaining / 60)}m)"
                else:
                    exp_str = " (EXPIRED)"

            print(f"  {rid}  {flag}")
            print(f"    Tool: {tool} | Target: {target} | Created: {created_str}{exp_str}")
            if note:
                print(f"    Note: {note}")
            print()
        return

    # ── Remove rule ──
    if action == "remove":
        rule_id = getattr(args, "rule_id", None)
        if not rule_id:
            print("Usage: obol allow remove <rule-id>")
            return
        try:
            from obol.hooks.allowlist import remove_rule
        except ImportError:
            print("Allowlist module not available.")
            return

        if remove_rule(rule_id):
            print(f"Rule {rule_id} removed.")
        else:
            print(f"Rule {rule_id} not found.")
        return

    # ── Add rule ──
    flag = action

    # Validate flag name
    try:
        from obol.hooks.messages import FLAG_MESSAGES
        if flag not in FLAG_MESSAGES:
            from difflib import get_close_matches
            matches = get_close_matches(flag, list(FLAG_MESSAGES.keys()), n=3, cutoff=0.5)
            if matches:
                print(f"Unknown flag: {flag}")
                print("Did you mean:")
                for m in matches:
                    print(f"  obol allow {m}")
                return
            print(f"Warning: '{flag}' is not a known detection flag.")
            print("Proceeding anyway (may be a custom/future flag).")
    except ImportError:
        pass

    try:
        from obol.hooks.allowlist import add_rule
    except ImportError:
        print("Allowlist module not available.")
        return

    tool = getattr(args, "tool", None)
    target_contains = getattr(args, "target_contains", None)
    note = getattr(args, "note", "") or ""
    expires = getattr(args, "expires", None)

    rule_id = add_rule(
        flag,
        tool=tool,
        target_contains=target_contains,
        note=note,
        expires_days=int(expires) if expires else None,
    )

    print(f"Allowlist rule created: {rule_id}")
    print(f"  Flag: {flag}")
    if tool:
        print(f"  Tool: {tool}")
    if target_contains:
        print(f"  Target contains: {target_contains}")
    if expires:
        print(f"  Expires in: {expires} days")
    print(f"\nView all rules: obol allow list")
    print(f"Remove: obol allow remove {rule_id}")


def setup_parser(subparsers):
    parser = subparsers.add_parser("allow", help="Manage detection allowlist")
    parser.add_argument("flag_or_action", nargs="?",
                        help="Flag name, 'list', or 'remove'")
    parser.add_argument("rule_id", nargs="?",
                        help="Rule ID (for 'remove' action)")
    parser.add_argument("--tool", "-t", help="Only apply to this tool")
    parser.add_argument("--target-contains", "-c",
                        help="Only when target contains this string")
    parser.add_argument("--note", "-n", help="Note explaining why")
    parser.add_argument("--expires", "-e",
                        help="Auto-expire in N days")
    parser.set_defaults(func=cmd_allow)
