
import time
import os
import sys
from pathlib import Path
from datetime import datetime
import urllib.request
import json

# Import Cortex components (assumes they are in the same dir or path)
sys.path.append(str(Path(__file__).parent))
try:
    from genesis_memory_cortex import WorkingMemoryCache
    from vector_backends import VectorManager
except ImportError:
    print("FATAL: Could not import Cortex components.")
    sys.exit(1)

LOCK_FILE = Path("E:/genesis-system/data/SYSTEM_LOCKDOWN.mode")
PULSE_FILE = Path("E:/genesis-system/data/heartbeat.pulse")

def check_pulse():
    """Checks connection to the Core (Redis + Qdrant)."""
    redis_ok = False
    qdrant_ok = False
    
    # 1. Check Redis
    try:
        # Use our modified Fail-Loud cache
        cache = WorkingMemoryCache(ssl=False) 
        if cache.available:
            redis_ok = True
    except Exception as e:
        print(f"❌ Redis Failure: {e}")

    # 2. Check Qdrant
    try:
        vm = VectorManager()
        health = vm.health()
        if health.get("qdrant"):
            qdrant_ok = True
        else:
            print("❌ Qdrant reported unhealthy.")
    except Exception as e:
        print(f"❌ Qdrant Failure: {e}")

    # 3. Check Health API (Claude's Service)
    health_api_ok = False
    try:
        with urllib.request.urlopen("http://localhost:8765/ping", timeout=2) as response:
            if response.status == 200:
                data = json.loads(response.read().decode())
                if data.get("status") == "ok":
                    health_api_ok = True
    except Exception as e:
        print(f"❌ Health API Failure: {e}")

    return redis_ok and qdrant_ok and health_api_ok

def cardiac_arrest():
    """Initiates System Lockdown."""
    if not LOCK_FILE.exists():
        with open(LOCK_FILE, "w") as f:
            f.write(f"CARDIAC ARREST INITIATED: {datetime.now().isoformat()}\n")
            f.write("REASON: Core Connection Lost or Health API Unresponsive.\n")
        print("\n🚨 SYSTEM LOCKDOWN INITIATED. CARDIAC ARREST.")
    
    if PULSE_FILE.exists():
        os.remove(PULSE_FILE)

def revive():
    """Lifts System Lockdown."""
    if LOCK_FILE.exists():
        os.remove(LOCK_FILE)
        print("\n✅ SYSTEM REVIVED. Connection restored.")
    
    with open(PULSE_FILE, "w") as f:
        f.write(datetime.now().isoformat())

def run_pacemaker():
    print("💓 Genesis Pacemaker Active. Monitoring Elestio Core...")
    while True:
        alive = check_pulse()
        
        if alive:
            revive()
            sys.stdout.write(".")
            sys.stdout.flush()
        else:
            cardiac_arrest()
            sys.stdout.write("!")
            sys.stdout.flush()
        
        time.sleep(10) # Check every 10 seconds

if __name__ == "__main__":
    run_pacemaker()
