"""
Health checks module
"""
from tests.utils.logger import Logger
from tests.utils.http_utils import HTTPUtils


class HealthChecks:
    """Check system health endpoints"""
    
    def __init__(self, logger: Logger, base_url: str = "http://localhost:8000", version: str = "unknown"):
        self.logger = logger
        self.version = version
        self.http_utils = HTTPUtils(logger, base_url)
    
    def run_all_checks(self) -> bool:
        """Run all health checks"""
        self.logger.subheader(f"Health Checks (v{self.version})")

        # Check backend health endpoint
        success, status_code, health_response = self.http_utils.get("/api/health")

        if not success:
            self.logger.error("HEALTH", f"Backend health endpoint check failed: {status_code}")
            return False

        if status_code == 503:
            self.logger.error("HEALTH", "Backend health endpoint: unhealthy")
            return False

        self.logger.success("HEALTH", "Backend health endpoint: healthy")

        # Check database connectivity via health endpoint (using cached response)
        if not self._check_database_health(health_response):
            return False

        # Check Redis connectivity via health endpoint (using cached response)
        if not self._check_redis_health(health_response):
            return False

        # Check nginx accessibility
        if not self._check_nginx():
            return False

        # Check caddy accessibility
        if not self._check_caddy():
            return False

        self.logger.success("HEALTH", "All health checks passed")
        return True

    def _check_database_health(self, health_response: dict) -> bool:
        """Check database connectivity via health endpoint (using cached response)"""
        self.logger.info("HEALTH", "Checking database connectivity...")

        db_status = health_response.get("database", "unknown")
        if db_status == "ok":
            self.logger.success("HEALTH", "Database: ok")
            return True
        else:
            self.logger.error("HEALTH", f"Database: {db_status}")
            return False

    def _check_redis_health(self, health_response: dict) -> bool:
        """Check Redis connectivity via health endpoint (using cached response)"""
        self.logger.info("HEALTH", "Checking Redis connectivity...")

        redis_status = health_response.get("redis", "unknown")
        if redis_status == "ok":
            self.logger.success("HEALTH", "Redis: ok")
            return True
        else:
            self.logger.error("HEALTH", f"Redis: {redis_status}")
            return False
    
    def _check_nginx(self) -> bool:
        """Check nginx accessibility"""
        self.logger.info("HEALTH", "Checking nginx accessibility...")
        
        if self.http_utils.check_port_open("localhost", 8080):
            self.logger.success("HEALTH", "Nginx: accessible on port 8080")
            return True
        else:
            self.logger.warning("HEALTH", "Nginx: not accessible on port 8080")
            return True  # Not critical for basic functionality
    
    def _check_caddy(self) -> bool:
        """Check caddy accessibility"""
        self.logger.info("HEALTH", "Checking Caddy accessibility...")
        
        # Check HTTP (port 80)
        if self.http_utils.check_port_open("localhost", 80):
            self.logger.success("HEALTH", "Caddy: accessible on port 80")
        else:
            self.logger.warning("HEALTH", "Caddy: not accessible on port 80")
        
        # Check HTTPS (port 443) - might not be available in dev
        if self.http_utils.check_port_open("localhost", 443):
            self.logger.success("HEALTH", "Caddy: accessible on port 443")
        else:
            self.logger.info("HEALTH", "Caddy: HTTPS not configured (expected in dev)")
        
        return True
