import os
import time
import json
import datetime
import sys
from pathlib import Path

# Add core to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
    from genesis_memory_cortex import MemoryCortex
    CORTEX_AVAILABLE = True
except ImportError:
    CORTEX_AVAILABLE = False

class ContinuityPulsar:
    """
    Pulsar Protocol: Ensures Genesis maintains momentum.
    Runs every 15 minutes to assess system status and suggest next steps.
    """
    def __init__(self, heartbeat_interval=900): # 15 minutes
        self.interval = heartbeat_interval
        self.status_file = Path(r"e:\genesis-system\data\CONTINUITY_STATUS.json")
        self.log_file = Path(r"e:\genesis-system\data\continuity_pulse.log")
        self.dashboard_file = Path(r"e:\genesis-system\HEARTBEAT_DASHBOARD.txt")
        self.cortex = MemoryCortex() if CORTEX_AVAILABLE else None
        
    def pulse(self):
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"💓 [PULSE] System Heartbeat at {timestamp}")
        
        # 1. Self-Diagnostics
        health = self._check_health()
        
        # 2. Idle-Time Consolidation (Memory System Upgrade)
        consolidation_stats = {}
        if self.cortex:
            try:
                print("  🧠 Running Memory Consolidation...")
                consolidation_stats = self.cortex.consolidate()
            except Exception as e:
                print(f"  ⚠️ Memory Consolidation Failed: {e}")
        
        status = {
            "last_pulse": timestamp,
            "system_health": health,
            "active_tasks": self._get_active_tasks(),
            "memory_stats": consolidation_stats,
            "suggested_next_steps": self._derive_next_steps()
        }
        
        # 3. Write Status Artifacts
        self._update_dashboard(status)
        
        with open(self.status_file, "w") as f:
            json.dump(status, f, indent=4)
            
        with open(self.log_file, "a") as f:
            f.write(f"[{timestamp}] Pulse emitted. Health: {health} | Promoted: {consolidation_stats.get('promoted', 0)}\n")

    def _update_dashboard(self, status):
        """Writes a human-readable dashboard for the user to keep open."""
        dashboard = f"""
===============================================================
   GENESIS CONTINUITY PULSAR | PID: {os.getpid()}
===============================================================
   Last Pulse: {status['last_pulse']}
   Health:     {status['system_health']}
   Tasks:      {status['active_tasks']}
===============================================================
   MEMORY CORTEX ACTION:
   - Promoted Memories: {status.get('memory_stats', {}).get('promoted', 0)}
   - Pruned Memories:   {status.get('memory_stats', {}).get('pruned', 0)}
===============================================================
   SUGGESTED NEXT STEPS:
   {chr(10).join(['- ' + step for step in status['suggested_next_steps']])}
===============================================================
   (This file updates every {self.interval} seconds)
"""
        with open(self.dashboard_file, "w") as f:
            f.write(dashboard)

    def _check_health(self):
        # Basic health checks
        checks = {
            "memory_cortex": os.path.exists(r"e:\genesis-system\data\episodic_memory.db"),
            "ghl_bridge": os.path.exists(r"e:\genesis-system\tools\ghl_mcp_bridge.py")
        }
        return "GREEN" if all(checks.values()) else "AMBER"

    def _get_active_tasks(self):
        # Read from task.md if possible
        task_md = Path(r"C:\Users\P3\.gemini\antigravity\brain\b5244881-3a2c-4228-9fdd-17696eef9e04\task.md")
        if task_md.exists():
            return "Task list available in task.md"
        return "No active task.md found."

    def _derive_next_steps(self):
        # Logic to suggest work when idle
        # 1. Run Tests
        # 2. Memory Pruning
        # 3. Pre-mortem Stress Tests
        return [
            "Run integration tests on built skills",
            "Perform memory digestion (night cycle simulation)",
            "Audit lead enrichment CSVs for accuracy",
            "Pre-mortem: What if the Telnyx API goes down?"
        ]

    def run_forever(self):
        print(f"🚀 Continuity Pulsar Activated. Interval: {self.interval}s")
        # Ensure we run immediately on start
        self.pulse()
        while True:
            time.sleep(self.interval)
            self.pulse()

if __name__ == "__main__":
    pulsar = ContinuityPulsar()
    pulsar.run_forever()
