#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Context Envelope: Captures git + session context for evidence items (Symposium P1 — Phase 4)

Every evidence item and episodic entry gets a context envelope showing
WHAT was happening when it was captured (git branch, recent files).

60s cache prevents subprocess spam during rapid bridge processing.
Dependencies: Python stdlib only (Law 4)
"""

import subprocess
import time
from datetime import datetime, timezone

_cache = {"data": None, "expires": 0.0}
CACHE_TTL = 60.0  # seconds


def _run_git(args: list, timeout: float = 2.0) -> str:
    """Run a git command with timeout + Windows encoding safety."""
    try:
        result = subprocess.run(
            ["git"] + args,
            capture_output=True, text=True,
            encoding="utf-8", errors="replace",
            timeout=timeout,
        )
        return result.stdout.strip() if result.returncode == 0 else ""
    except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
        return ""


def get_context_envelope() -> dict:
    """Get current git + session context. Cached for 60s."""
    now = time.time()
    if _cache["data"] and now < _cache["expires"]:
        return _cache["data"]

    branch = _run_git(["branch", "--show-current"]) or "unknown"
    recent_files_raw = _run_git(["diff", "--name-only", "HEAD~1"])
    if not recent_files_raw:
        # Fallback: staged files or last commit files
        recent_files_raw = _run_git(["diff", "--name-only", "--cached"])
    recent_files = [f for f in recent_files_raw.split("\n") if f.strip()][:5]

    envelope = {
        "git_branch": branch,
        "recent_files": recent_files,
        "captured_at": datetime.now(timezone.utc).isoformat(),
    }

    _cache["data"] = envelope
    _cache["expires"] = now + CACHE_TTL
    return envelope
