import time
import requests
import logging
from .metrics import MetricsCollector

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class HealthMonitor:
    def __init__(self, qwen_url, elestio_url, interval=60):
        self.qwen_url = qwen_url
        self.elestio_url = elestio_url
        self.interval = interval
        self.metrics_collector = MetricsCollector()

    def check_service_health(self, url, service_name):
        try:
            response = requests.get(url, timeout=10)
            response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
            self.metrics_collector.increment_success(service_name)
            logging.info(f"{service_name} is healthy.")
            return True
        except requests.exceptions.RequestException as e:
            self.metrics_collector.increment_failure(service_name)
            logging.error(f"Error checking {service_name} health: {e}")
            return False

    def run(self):
        logging.info("Health monitor started.")
        while True:
            self.check_service_health(self.qwen_url, "Qwen")
            self.check_service_health(self.elestio_url, "Elestio")
            time.sleep(self.interval)


if __name__ == '__main__':
    # Example usage (replace with actual URLs)
    qwen_url = "http://localhost:8000/health"
    elestio_url = "http://localhost:8001/health"

    monitor = HealthMonitor(qwen_url, elestio_url)
    monitor.run()