#!/usr/bin/env python3
"""
Genesis C: Drive Cleanup Hook — Stop Event
==========================================
Runs at session end to clean ephemeral Claude Code files from C: drive.
Calls the PowerShell script via Windows-native path (not WSL) to avoid
Antigravity profile interception.

Targets:
  C:\\Users\\P3\\.claude\\debug\\        — Session debug transcripts
  C:\\Users\\P3\\.claude\\todos\\        — Per-session todo JSON files
  C:\\Users\\P3\\.claude\\shell-snapshots\\ — Bash shell snapshots
  C:\\Users\\P3\\.claude\\projects\\C--* — Dead C: drive worktree project dirs

Author: Genesis Command Centre
"""

import sys
import json
import os
import subprocess
from datetime import datetime, timezone
from pathlib import Path

GENESIS_ROOT = Path("/mnt/e/genesis-system")
CLEANUP_SCRIPT = r"E:\genesis-system\scripts\c_drive_cleanup.ps1"
LOG_DIR = GENESIS_ROOT / "data" / "cleanup_logs"
LOG_FILE = LOG_DIR / f"c_drive_cleanup_{datetime.now().strftime('%Y-%m-%d')}.log"

# Minimum interval between cleanups (minutes) — prevents hammering on every stop
MIN_INTERVAL_MINUTES = 30
LAST_RUN_FILE = GENESIS_ROOT / "data" / "context_state" / "last_c_cleanup.json"


def should_run() -> bool:
    """Rate-limit: only run if MIN_INTERVAL_MINUTES have passed since last run."""
    try:
        if LAST_RUN_FILE.exists():
            with open(LAST_RUN_FILE) as f:
                data = json.load(f)
            last_run = datetime.fromisoformat(data.get("last_run", "2000-01-01T00:00:00+00:00"))
            elapsed = (datetime.now(timezone.utc) - last_run).total_seconds() / 60
            if elapsed < MIN_INTERVAL_MINUTES:
                return False
    except Exception:
        pass
    return True


def mark_run():
    """Record that cleanup ran now."""
    try:
        LAST_RUN_FILE.parent.mkdir(parents=True, exist_ok=True)
        with open(LAST_RUN_FILE, "w") as f:
            json.dump({"last_run": datetime.now(timezone.utc).isoformat()}, f)
    except Exception:
        pass


def log(message: str):
    try:
        LOG_DIR.mkdir(parents=True, exist_ok=True)
        timestamp = datetime.now(timezone.utc).isoformat()
        with open(LOG_FILE, "a") as f:
            f.write(f"[{timestamp}] [hook] {message}\n")
    except Exception:
        pass


def run_cleanup():
    """
    Execute the PowerShell cleanup script.
    Uses cmd.exe → powershell to avoid WSL/Antigravity interception.
    """
    try:
        # Use wsl.exe to invoke powershell.exe (Windows-side) from WSL
        # This bypasses the Antigravity bash profile since we're calling powershell, not bash
        result = subprocess.run(
            [
                "powershell.exe",
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy", "Bypass",
                "-File", CLEANUP_SCRIPT
            ],
            capture_output=True,
            text=True,
            timeout=60
        )
        
        stdout = result.stdout.strip()
        stderr = result.stderr.strip()
        
        if stdout:
            log(f"stdout: {stdout}")
        if stderr:
            log(f"stderr: {stderr}")
        
        log(f"exit_code: {result.returncode}")
        return result.returncode == 0, stdout
        
    except subprocess.TimeoutExpired:
        log("ERROR: cleanup script timed out after 60s")
        return False, "timeout"
    except FileNotFoundError:
        # powershell.exe not found — we're not in WSL with Windows access
        log("SKIP: powershell.exe not found (not running in WSL)")
        return True, "skipped - not in WSL"
    except Exception as e:
        log(f"ERROR: {e}")
        return False, str(e)


def main():
    try:
        hook_input = json.loads(sys.stdin.read())
    except Exception:
        hook_input = {}

    # Only run periodically (rate-limited)
    if not should_run():
        print(json.dumps({}))
        return

    log("=== C: Drive Cleanup Hook Triggered ===")
    mark_run()
    
    success, output = run_cleanup()
    
    result = {}
    
    if not success:
        # Don't block session stop on cleanup failure
        log(f"Cleanup failed but not blocking stop: {output}")
    else:
        # If cleanup reported deletions, surface in additionalContext
        if output and "Removed" in output and "0 " not in output:
            result["additionalContext"] = f"🧹 C: drive cleanup ran: {output}"
        log(f"Cleanup succeeded: {output}")
    
    print(json.dumps(result))


if __name__ == "__main__":
    main()
