"""Session metadata and chatmap discovery utilities."""

import json
from pathlib import Path
from typing import Optional, Set

from .paths import SESSION_BASE


def find_session_metadata(
    expected_dir: Optional[Path] = None,
    exclude_paths: Optional[Set[Path]] = None,
) -> Optional[dict]:
    """Find metadata.json across all sessions, with filtering.

    Scans SESSION_BASE/*/metadata.json. Returns the first match that:
    - Has session_id and/or transcript_path
    - transcript_path parent matches expected_dir (if given)
    - transcript_path not in exclude_paths (if given)
    """
    if not SESSION_BASE.is_dir():
        return None

    for meta_file in SESSION_BASE.glob("*/metadata.json"):
        try:
            data = json.loads(meta_file.read_text())
        except (json.JSONDecodeError, OSError):
            continue

        sid = data.get("session_id")
        tp = data.get("transcript_path")
        if not sid and not tp:
            continue

        if tp:
            tp_path = Path(tp)
            if expected_dir is not None and tp_path.parent != expected_dir:
                continue
            if exclude_paths and tp_path in exclude_paths:
                continue

        return data

    return None


def discover_chatmap(session_id: Optional[str] = None) -> Optional[Path]:
    """Find a chatmap.json file.

    If session_id is given, returns that session's chatmap.json (or None).
    Otherwise, returns the most recently modified chatmap.json across all sessions.
    """
    if session_id:
        p = SESSION_BASE / session_id / "chatmap.json"
        return p if p.exists() else None

    if not SESSION_BASE.is_dir():
        return None

    candidates = list(SESSION_BASE.glob("*/chatmap.json"))
    if not candidates:
        return None

    return max(candidates, key=lambda f: f.stat().st_mtime)
