#!/usr/bin/env python3
"""
Session Sync Hook for Genesis
Runs on Claude Code session start to auto-sync with Antigravity agent state.

Reads:
- Latest Antigravity handoff
- Recent events since last sync
- Task board state
- Active file locks

Outputs concise summary as additionalContext (<2000 chars).
"""

import json
import sys
from datetime import datetime, timezone
from pathlib import Path

SYNC_DIR = Path("/mnt/e/genesis-system/data/antigravity-sync")
EVENTS_FILE = SYNC_DIR / "events.jsonl"
TASKBOARD_FILE = SYNC_DIR / "taskboard.json"
HANDOFFS_DIR = SYNC_DIR / "handoffs"
LOCK_FILE = SYNC_DIR / "file_locks.json"
SYNC_STATE_FILE = SYNC_DIR / "claude_last_sync.json"


def get_last_sync() -> str:
    """Get timestamp of last sync."""
    try:
        if SYNC_STATE_FILE.exists():
            with open(SYNC_STATE_FILE, "r") as f:
                data = json.load(f)
                return data.get("last_sync", "")
    except Exception:
        pass
    return ""


def get_recent_events(since: str, limit: int = 20) -> list:
    """Get events from antigravity agent since timestamp."""
    events = []
    try:
        if EVENTS_FILE.exists():
            with open(EVENTS_FILE, "r") as f:
                for line in f:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        event = json.loads(line)
                        if event.get("source") in ("antigravity", "execution_bridge"):
                            if not since or event.get("timestamp", "") > since:
                                events.append(event)
                    except json.JSONDecodeError:
                        continue
    except Exception:
        pass
    return events[-limit:]


def get_latest_handoff() -> dict:
    """Read latest antigravity handoff."""
    try:
        handoff_file = HANDOFFS_DIR / "LATEST_antigravity.json"
        if handoff_file.exists():
            with open(handoff_file, "r") as f:
                return json.load(f)
    except Exception:
        pass
    return {}


def get_pending_tasks() -> list:
    """Get pending tasks from taskboard."""
    try:
        if TASKBOARD_FILE.exists():
            with open(TASKBOARD_FILE, "r") as f:
                data = json.load(f)
                tasks = data.get("tasks", [])
                return [t for t in tasks if t.get("status") in ("pending", "in_progress")]
    except Exception:
        pass
    return []


def get_active_locks() -> dict:
    """Get active file locks."""
    now = datetime.now(timezone.utc)
    locks = {}
    try:
        if LOCK_FILE.exists():
            with open(LOCK_FILE, "r") as f:
                all_locks = json.load(f)
                for path, info in all_locks.items():
                    expires = datetime.fromisoformat(info["expires_at"])
                    if expires > now:
                        locks[path] = info
    except Exception:
        pass
    return locks


def build_summary() -> str:
    """Build concise sync summary."""
    last_sync = get_last_sync()
    events = get_recent_events(last_sync)
    handoff = get_latest_handoff()
    tasks = get_pending_tasks()
    locks = get_active_locks()

    parts = []

    # Check if there's anything to report
    has_data = events or handoff or tasks or locks
    if not has_data:
        return ""

    parts.append("[Antigravity Sync]")

    # Latest handoff
    if handoff:
        ts = handoff.get("timestamp", "?")[:19]
        summary = handoff.get("summary", "")[:200]
        files_count = len(handoff.get("files_changed", []))
        actions = handoff.get("next_actions", [])
        parts.append(f"Last handoff ({ts}): {summary}")
        if files_count:
            parts.append(f"  Files changed: {files_count}")
        if actions:
            parts.append(f"  Next: {'; '.join(str(a)[:60] for a in actions[:3])}")

    # Recent events
    if events:
        parts.append(f"Events since last sync: {len(events)}")
        for e in events[-5:]:
            etype = e.get("type", "?")
            esrc = e.get("source", "?")
            parts.append(f"  [{esrc}] {etype}")

    # Pending tasks
    if tasks:
        parts.append(f"Pending tasks: {len(tasks)}")
        for t in tasks[:5]:
            title = t.get("title", "?")[:50]
            status = t.get("status", "?")
            claimed = t.get("claimed_by", "unclaimed")
            parts.append(f"  [{status}] {title} ({claimed})")

    # File locks
    if locks:
        parts.append(f"Active file locks: {len(locks)}")
        for path, info in list(locks.items())[:5]:
            agent = info.get("agent", "?")
            parts.append(f"  {path} -> {agent}")

    # Truncate to 2000 chars
    summary = "\n".join(parts)
    if len(summary) > 2000:
        summary = summary[:1997] + "..."

    return summary


def main():
    """Main hook entry point."""
    try:
        summary = build_summary()

        # Update last sync timestamp
        now = datetime.now(timezone.utc).isoformat()
        try:
            SYNC_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
            with open(SYNC_STATE_FILE, "w") as f:
                json.dump({"last_sync": now}, f)
        except Exception:
            pass

        if summary:
            print(json.dumps({"additionalContext": summary}))
        else:
            print(json.dumps({}))

    except Exception as e:
        # Hook should never block session start
        print(json.dumps({}))


if __name__ == "__main__":
    main()
