"""obol review - show session detection summary.

Reads the most recent session state and displays all detections with
human-readable explanations.

    obol review                  Show current/latest session
    obol review --session SID    Show specific session
"""
import hashlib
import json
import os
import sys
import time


SESSIONS_DIR = os.path.expanduser("~/.obol/sessions")


def _find_latest_session():
    """Find the most recently modified session file."""
    if not os.path.isdir(SESSIONS_DIR):
        return None
    best = None
    best_mtime = 0
    for fname in os.listdir(SESSIONS_DIR):
        if not fname.endswith(".json"):
            continue
        fpath = os.path.join(SESSIONS_DIR, fname)
        mtime = os.path.getmtime(fpath)
        if mtime > best_mtime:
            best = fpath
            best_mtime = mtime
    return best


def _load_session(path):
    """Load session state from file."""
    with open(path) as f:
        return json.load(f)


def cmd_review(args):
    sid = getattr(args, "session", None)
    if sid:
        sid_hash = hashlib.sha256(sid.encode()).hexdigest()[:16]
        path = os.path.join(SESSIONS_DIR, f"{sid_hash}.json")
    else:
        path = _find_latest_session()

    if not path or not os.path.exists(path):
        print("No session data found.")
        if not os.path.isdir(SESSIONS_DIR):
            print(f"Sessions directory does not exist: {SESSIONS_DIR}")
        return

    try:
        state = _load_session(path)
    except Exception as e:
        print(f"Error reading session: {e}")
        return

    ux = state.get("ux_stats", {})
    if not ux:
        print("No UX stats in this session (pre-UX-overhaul session).")
        print(f"Session events: {state.get('total_count', '?')}")
        return

    # Import messages module for formatting
    try:
        from obol.hooks.messages import (
            format_session_summary, get_flag_title, get_flag_explanation,
            get_user_severity,
        )
        has_messages = True
    except ImportError:
        has_messages = False

    total = ux.get("total", 0)
    clean = ux.get("clean", 0)
    flagged = ux.get("flagged", 0)
    deferred = ux.get("deferred", [])
    session_start = ux.get("session_start", 0)

    # Print summary
    if has_messages:
        print(format_session_summary(ux))
    else:
        print(f"Session: {total} events, {clean} clean, {flagged} flagged")

    if not deferred:
        return

    # Detailed view of each detection
    print("Detailed Detections:")
    print("-" * 50)

    # Group by flag
    seen = {}
    for entry in deferred:
        if len(entry) >= 4:
            flag, tool, target, ts = entry[0], entry[1], entry[2], entry[3]
        elif len(entry) >= 1:
            flag = entry[0]
            tool = entry[1] if len(entry) > 1 else ""
            target = entry[2] if len(entry) > 2 else ""
            ts = entry[3] if len(entry) > 3 else 0
        else:
            continue

        if flag not in seen:
            seen[flag] = []
        seen[flag].append({"tool": tool, "target": target, "ts": ts})

    for flag, occurrences in seen.items():
        if has_messages:
            title = get_flag_title(flag)
            explanation = get_flag_explanation(flag)
            sev = get_user_severity(flag)
        else:
            title = flag
            explanation = ""
            sev = "?"

        count = len(occurrences)
        count_str = f" ({count}x)" if count > 1 else ""
        print(f"\n  [{sev}] {title}{count_str}")
        if explanation:
            print(f"  {explanation}")
        for occ in occurrences[:5]:
            ts_str = ""
            if occ["ts"]:
                ts_str = time.strftime("%H:%M:%S", time.localtime(occ["ts"]))
            parts = []
            if ts_str:
                parts.append(ts_str)
            if occ["tool"]:
                parts.append(occ["tool"])
            if occ["target"]:
                parts.append(occ["target"][:60])
            if parts:
                print(f"    {' | '.join(parts)}")
        if count > 5:
            print(f"    ... and {count - 5} more")

    # Suggest allowlist for repeated low-severity flags
    repeated_low = [f for f, occs in seen.items()
                    if len(occs) >= 2 and has_messages
                    and get_user_severity(f) in ("INFO", "FYI")]
    if repeated_low:
        print("\nRepeated low-severity flags (consider allowlisting):")
        for f in repeated_low:
            print(f"  obol allow {f}")


def setup_parser(subparsers):
    parser = subparsers.add_parser("review", help="Session detection summary")
    parser.add_argument("--session", "-s", help="Session ID (default: latest)")
    parser.set_defaults(func=cmd_review)
