import os
import time
import json
import logging
from datetime import datetime
from typing import List, Dict, Any

# Mocking parts of Genesis core if not directly importable
# In a real scenario, we'd import from core.ghl_client etc.
try:
    from core.ghl_mcp_bridge import GHLMCPBridge
except ImportError:
    # Handle environment where bridge is in tools/
    import sys
    sys.path.append('E:/genesis-system/tools')
    from ghl_mcp_bridge import GHLMCPBridge

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("RevenueMonitor")

class HealthStatus:
    def __init__(self, status: str, failed_checks: List[str]):
        self.status = status
        self.failed_checks = failed_checks

class RevenueProtectionMonitor:
    """
    Ensures 1k/24h mission critical uptime.
    Monitors GHL, Voice, and Integration health.
    """
    
    def __init__(self, ghl_mcp_path: str = r"E:\genesis-system\mcp-servers\ghl"):
        self.ghl_mcp_path = ghl_mcp_path
        # Default keys from GENESIS MASTER CREDENTIALS
        self.agency_key = os.getenv("GHL_AGENCY_KEY", "pit-b9be7195-e808-4f95-a984-34f9dcab51c4")
        self.location_id = os.getenv("GHL_LOCATION_ID", "hi579yZXCwI6evayt25C")

    def get_active_clients(self) -> List[Dict[str, Any]]:
        """
        Get list of clients to monitor.
        For now, returns the playground/template as the primary client.
        """
        return [
            {
                "id": "playground",
                "name": "Tradie Chatbots - Genesis Test 1",
                "location_id": self.location_id,
                "tier": 1
            }
        ]

    def check_ghl_connectivity(self, location_id: str) -> bool:
        """Verifies if GHL API responds for this location."""
        bridge = GHLMCPBridge(self.ghl_mcp_path)
        bridge.env["GHL_API_KEY"] = self.agency_key
        try:
            res = bridge.call_tool("get_location", {"locationId": location_id})
            return "result" in res
        except Exception as e:
            logger.error(f"GHL Check Failed for {location_id}: {e}")
            return False
        finally:
            bridge.stop()

    def health_check(self, client: Dict[str, Any]) -> HealthStatus:
        logger.info(f"Checking health for {client['name']}...")
        
        checks = {
            "ghl_api": self.check_ghl_connectivity(client["location_id"]),
            # Add Vapi, Telnyx checks here as per REV-011+
        }
        
        failed = [k for k, v in checks.items() if not v]
        status = "healthy" if not failed else "unhealthy"
        
        return HealthStatus(status, failed)

    def run_cycle(self):
        clients = self.get_active_clients()
        for client in clients:
            health = self.health_check(client)
            if health.status != "healthy":
                logger.warning(f"🚨 ALERT: Client {client['name']} is UNHEALTHY! Failed: {health.failed_checks}")
                # TODO: Trigger recovery logic (REV-007)
            else:
                logger.info(f"✅ Client {client['name']} is healthy.")

if __name__ == "__main__":
    monitor = RevenueProtectionMonitor()
    logger.info("Starting Revenue Protection Monitor Cycle...")
    monitor.run_cycle()
