#!/usr/bin/env python3
"""
boot_context_inject.py — Bulletproof SessionStart hook
=======================================================
Always fires. Always injects. No DB. No network. No wrong paths.

Reads BOOT_CONTEXT.md from the repo and injects it as additionalContext.
This is the FIRST hook in the SessionStart chain — ensures Claude always
boots with mission context even if Sunaiva DB is down or MEMORY.md is missing.

The BOOT_CONTEXT.md file lives at:
  /mnt/e/genesis-system/data/context_state/BOOT_CONTEXT.md

Maintain it manually after major mission changes.
"""

import json
import sys
from pathlib import Path

BOOT_CONTEXT = Path("/mnt/e/genesis-system/data/context_state/BOOT_CONTEXT.md")
HANDOFF_DIR = Path("/mnt/e/genesis-system/hive/progress")


def get_latest_handoff_snippet() -> str:
    """Get just the mission-relevant parts of the latest handoff."""
    try:
        handoffs = sorted(
            HANDOFF_DIR.glob("session_*_handoff.md"),
            key=lambda f: f.stat().st_mtime,
            reverse=True
        )
        if not handoffs:
            return ""
        
        latest = handoffs[0]
        content = latest.read_text(encoding="utf-8", errors="replace")
        session_num = latest.stem.replace("session_", "").replace("_handoff", "")
        
        # Only include if it has actual narrative (not just metrics)
        if len(content) > 500:
            return f"\n\n---\n## Latest Handoff (Session {session_num})\n{content[:2000]}"
        return f"\n\n---\n## Latest Handoff: Session {session_num} (metrics only — see BOOT_CONTEXT above)"
    except Exception:
        return ""


def main():
    try:
        # Read stdin (hook input) but we don't need it
        sys.stdin.read()
    except Exception:
        pass

    try:
        if not BOOT_CONTEXT.exists():
            # Fallback minimal context if file is missing
            context = """## GENESIS BOOT (minimal fallback)
Mission: ReceptionistAI — Australian AI Voice Agents
- Telnyx assistant: assistant-9c42d3ce-e05a-4e34-8083-c91081917637
- George's assistant: assistant-6f6f4ca2-3155-4930-95cb-27f59514af3e (needs phone number)
- All work on E: drive — C: drive is FULL
- NEVER SSH 152.53.201.152 (AIVA)
- Greet Kinan with what you are ALREADY doing, not questions
Update E:/genesis-system/data/context_state/BOOT_CONTEXT.md for full context."""
        else:
            context = BOOT_CONTEXT.read_text(encoding="utf-8", errors="replace")
        
        # Append latest handoff snippet
        context += get_latest_handoff_snippet()

        print(json.dumps({
            "hookSpecificOutput": {
                "hookEventName": "SessionStart",
                "additionalContext": context
            }
        }))

    except Exception as e:
        # Never crash — return empty JSON so Claude Code continues
        print(json.dumps({}))


if __name__ == "__main__":
    main()
