"""obol explain - explain a detection flag or event.

    obol explain reverse_shell       Explain a flag
    obol explain piped_exfiltration  Explain a flag
"""


def cmd_explain(args):
    flag_or_id = getattr(args, "flag", None)
    if not flag_or_id:
        print("Usage: obol explain <flag_name>")
        print("Example: obol explain reverse_shell")
        return

    # Import messages module
    try:
        from obol.hooks.messages import (
            FLAG_MESSAGES, get_flag_title, get_flag_explanation,
            get_user_severity,
        )
        has_messages = True
    except ImportError:
        has_messages = False
        print("Messages module not available. Install obol SDK.")
        return

    # Check if it's a known flag name
    if flag_or_id in FLAG_MESSAGES:
        entry = FLAG_MESSAGES[flag_or_id]
        sev = entry["user_severity"]
        print(f"\n  {entry['title']}  [{sev}]")
        print(f"  Flag: {flag_or_id}")
        print(f"  {entry['explanation']}")

        # Show severity tier context
        sev_context = {
            "CRITICAL": "Always interrupts immediately. Indicates an active attack or data loss.",
            "WARNING": "Interrupts if corroborated by other flags. Indicates suspicious activity.",
            "INFO": "Logged for review. Shows up in session summary.",
            "FYI": "Informational only. Appears in detailed review.",
        }
        print(f"\n  Severity: {sev_context.get(sev, sev)}")

        # Check allowlist
        try:
            from obol.hooks.allowlist import list_rules
            rules = list_rules()
            matching = [r for r in rules if r.get("flag") == flag_or_id]
            if matching:
                print(f"\n  Allowlisted: Yes ({len(matching)} rule(s))")
                for r in matching:
                    note = r.get("note", "")
                    tool = r.get("tool", "any tool")
                    target = r.get("target_contains", "any target")
                    print(f"    Rule {r.get('id', '?')}: {tool}, {target}"
                          + (f" — {note}" if note else ""))
            else:
                print(f"\n  Allowlisted: No")
                print(f"  To suppress: obol allow {flag_or_id}")
        except ImportError:
            pass

        # Show related flags (same severity tier)
        related = [f for f, e in FLAG_MESSAGES.items()
                   if e["user_severity"] == sev and f != flag_or_id]
        if related:
            print(f"\n  Related flags ({sev}):")
            for r in related[:6]:
                print(f"    {r}: {FLAG_MESSAGES[r]['title']}")
            if len(related) > 6:
                print(f"    ... and {len(related) - 6} more")
        print()
        return

    # Not a known flag — check if it looks like a flag name
    # and suggest closest matches
    from difflib import get_close_matches
    all_flags = list(FLAG_MESSAGES.keys())
    matches = get_close_matches(flag_or_id, all_flags, n=3, cutoff=0.5)

    if matches:
        print(f"Unknown flag: {flag_or_id}")
        print(f"Did you mean:")
        for m in matches:
            print(f"  obol explain {m}  — {FLAG_MESSAGES[m]['title']}")
    else:
        print(f"Unknown flag: {flag_or_id}")
        print(f"\nAvailable flags ({len(all_flags)}):")
        # Group by severity
        for sev in ("CRITICAL", "WARNING", "INFO", "FYI"):
            flags_in_tier = [f for f in all_flags
                             if FLAG_MESSAGES[f]["user_severity"] == sev]
            if flags_in_tier:
                print(f"\n  {sev}:")
                for f in sorted(flags_in_tier):
                    print(f"    {f}")


def setup_parser(subparsers):
    parser = subparsers.add_parser("explain", help="Explain a detection flag")
    parser.add_argument("flag", nargs="?", help="Flag name (e.g. reverse_shell)")
    parser.set_defaults(func=cmd_explain)
