#!/usr/bin/env python3
"""
Genesis Context Tracker - PostToolUse Hook (Layer 2 of 4)
Reads context state from StatusLine state file and injects warnings.

Thresholds (Kinan Directive 2026-02-25):
  50% → CTM checkpoint (save to supermemory)
  65% → CTM + RESPAWN (wrap up + respawn)
  70% → HARD CTM + FORCED RESPAWN (immediate stop)
"""
import sys
import json
import os
from pathlib import Path
from datetime import datetime, timezone

STATE_DIR = Path("/mnt/e/genesis-system/data/context_state")
STATE_DIR.mkdir(parents=True, exist_ok=True)
CTM_LOG = STATE_DIR / "ctm_triggers.jsonl"

CTM_THRESHOLD = 50
WARNING_THRESHOLD = 65       # CTM + respawn (aligned with auto_respawn.py)
CRITICAL_THRESHOLD = 70      # Hard CTM + forced respawn (Kinan directive 2026-02-25)


def get_context_from_state_file() -> dict:
    """Read context state from statusline-generated file."""
    state_file = STATE_DIR / "current.json"
    if state_file.exists():
        try:
            with open(state_file, "r") as f:
                return json.load(f)
        except Exception:
            pass
    return {}


def already_triggered_ctm(pct: float) -> bool:
    """Check if CTM was already triggered at this threshold band."""
    if not CTM_LOG.exists():
        return False
    try:
        with open(CTM_LOG, "r") as f:
            for line in f:
                entry = json.loads(line.strip())
                if (entry.get("event") == "ctm_trigger" and
                        abs(entry.get("percentage", 0) - pct) < 10):
                    return True
    except Exception:
        pass
    return False


def log_ctm_trigger(pct: float, source: str):
    """Log CTM trigger event."""
    try:
        event = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "event": "ctm_trigger",
            "percentage": round(pct, 1),
            "source": source,
        }
        with open(CTM_LOG, "a") as f:
            f.write(json.dumps(event) + "\n")
    except Exception:
        pass


def main():
    try:
        hook_input = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, Exception):
        print(json.dumps({}))
        return

    state = get_context_from_state_file()
    pct = state.get("used_percentage", 0)
    actual_free = state.get("actual_free", 100)

    additional_context = None

    if pct >= CRITICAL_THRESHOLD:
        additional_context = (
            f"CRITICAL CONTEXT WARNING: {pct:.0f}% used, {actual_free:.0f}% actual free. "
            "Context compaction is imminent. IMMEDIATELY: "
            "1) Save all progress to supermemory, "
            "2) Update MEMORY.md with war room status, "
            "3) Run /compact with preservation instructions."
        )
    elif pct >= WARNING_THRESHOLD:
        additional_context = (
            f"CONTEXT WARNING: {pct:.0f}% used, {actual_free:.0f}% actual free. "
            "Begin wrapping up current task. Run CTM protocol soon."
        )
    elif pct >= CTM_THRESHOLD:
        if not already_triggered_ctm(pct):
            log_ctm_trigger(pct, "post_tool_use")
            additional_context = (
                f"CTM CHECKPOINT: Context at {pct:.0f}%. "
                "Per Immortal Session Protocol: Save mission state, decisions, "
                "and blockers to supermemory genesis-kinan. "
                "Update MEMORY.md with critical context."
            )

    result = {}
    if additional_context:
        result["additionalContext"] = additional_context

    print(json.dumps(result))


if __name__ == "__main__":
    main()
