"""
Terminal Broker session-start hook for Claude Code.

Checks all broker channels for unread messages and prints a summary.
Silent if no unread messages exist.

Runnable as:
  python -m brynq.hooks
  python -m brynq.hooks --session-id my-session

Environment:
  BROKER_SESSION_ID  — Override session ID (default: random 8 hex chars)
  BROKER_DIR         — Override storage directory
"""

import argparse
import json
import os
import sys
import uuid
from pathlib import Path


PROJECT_ROOT = Path(__file__).resolve().parents[2]
BROKER_DIR = Path(os.environ.get("BROKER_DIR", PROJECT_ROOT / "state" / "broker"))
CHANNELS_DIR = BROKER_DIR / "channels"
CURSORS_DIR = BROKER_DIR / "cursors"


def _read_cursor(session_id: str, channel: str) -> int:
    path = CURSORS_DIR / f"{session_id}_{channel}.cursor"
    try:
        return int(path.read_text("utf-8").strip())
    except (FileNotFoundError, ValueError):
        return 0


def _read_jsonl(path: Path, offset: int = 0) -> list[dict]:
    if not path.exists():
        return []
    lines = path.read_text("utf-8").strip().splitlines()
    entries = []
    for line in lines[offset:]:
        try:
            entries.append(json.loads(line))
        except json.JSONDecodeError:
            continue
    return entries


def check_inbox(session_id: str) -> None:
    """Check all channels for unread messages. Print summary or stay silent."""
    if not CHANNELS_DIR.is_dir():
        return

    channel_files = sorted(CHANNELS_DIR.glob("*.jsonl"))
    if not channel_files:
        return

    unread_channels: list[tuple[str, int, str]] = []  # (channel, count, sender)
    total_unread = 0

    for f in channel_files:
        channel = f.stem
        all_lines = f.read_text("utf-8").strip().splitlines()
        total = len(all_lines)
        cursor = _read_cursor(session_id, channel)
        unread = max(0, total - cursor)

        if unread > 0:
            total_unread += unread
            # Find the latest sender among unread messages
            unread_msgs = _read_jsonl(f, offset=cursor)
            senders: dict[str, int] = {}
            for m in unread_msgs:
                name = m.get("session_name", "unknown")
                plat = m.get("platform", "?")
                key = f"{name}@{plat}"
                senders[key] = senders.get(key, 0) + 1
            # Build sender summary
            sender_parts = []
            for sender, count in senders.items():
                sender_parts.append(f"{count} new from {sender}")
            sender_summary = ", ".join(sender_parts)
            unread_channels.append((channel, unread, sender_summary))

    if total_unread == 0:
        return

    print(f"[Broker] {total_unread} unread message{'s' if total_unread != 1 else ''}:")
    for channel, count, sender_summary in unread_channels:
        print(f"  #{channel}: {sender_summary}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Broker inbox check hook")
    # Use persistent session ID resolution instead of random
    from .server import _resolve_session_id
    default_sid = _resolve_session_id()
    parser.add_argument(
        "--session-id",
        default=default_sid,
        help="Session ID for cursor tracking (default: BROKER_SESSION_ID env or persisted)",
    )
    args = parser.parse_args()

    try:
        check_inbox(args.session_id)
    except Exception:
        # Hook must never block session start
        pass


if __name__ == "__main__":
    main()
