"""
Environment variables checks module
"""
import os
from pathlib import Path
from tests.utils.logger import Logger


class EnvironmentChecks:
    """Check environment variables configuration"""
    
    def __init__(self, logger: Logger, project_dir: str, version: str = "unknown"):
        self.logger = logger
        self.version = version
        self.project_dir = Path(project_dir)
        self.env_path = self.project_dir / ".env"
        # Load environment variables once during initialization
        if self.env_path.exists():
            from dotenv import load_dotenv
            load_dotenv(self.env_path)
    
    def run_all_checks(self) -> bool:
        """Run all environment variable checks"""
        self.logger.subheader(f"Environment Variables Check (v{self.version})")
        
        all_ok = True
        
        # Check if .env file exists
        if not self._check_env_file():
            all_ok = False
        
        # Check required variables
        if self.env_path.exists():
            if not self._check_required_variables():
                all_ok = False
            
            # Check security of variables
            if not self._check_variable_security():
                all_ok = False
        
        if all_ok:
            self.logger.success("ENV", "All environment variable checks passed")
        else:
            self.logger.error("ENV", "Some environment variable checks failed")
        
        return all_ok
    
    def _check_env_file(self) -> bool:
        """Check if .env file exists"""
        self.logger.info("ENV", "Checking .env file...")
        
        if self.env_path.exists():
            self.logger.success("ENV", ".env file exists ✓")
            return True
        else:
            self.logger.error("ENV", ".env file not found")
            self.logger.info("ENV", "Create .env file from .env.example")
            return False
    
    def _check_required_variables(self) -> bool:
        """Check if all required variables are set"""
        self.logger.info("ENV", "Checking required variables...")
        
        required_vars = {
            "POSTGRES_PASSWORD": "Database password",
            "REDIS_PASSWORD": "Redis password",
            "JWT_SECRET_KEY": "JWT secret key",
            "ALLOWED_ORIGINS": "Allowed CORS origins",
        }
        
        all_ok = True
        for var_name, description in required_vars.items():
            value = os.getenv(var_name)
            if value and value.strip():
                self.logger.success("ENV", f"{var_name}: set ✓")
            else:
                self.logger.error("ENV", f"{var_name}: not set ({description})")
                all_ok = False
        
        return all_ok
    
    def _check_variable_security(self) -> bool:
        """Check security of environment variables"""
        self.logger.info("ENV", "Checking variable security...")
        
        all_ok = True
        warnings = []
        
        # Check POSTGRES_PASSWORD
        postgres_password = os.getenv("POSTGRES_PASSWORD", "")
        if postgres_password in ["", "postgres", "password", "123456", "admin"]:
            self.logger.error("ENV", "POSTGRES_PASSWORD: using insecure default value")
            all_ok = False
        elif len(postgres_password) < 12:
            self.logger.warning("ENV", "POSTGRES_PASSWORD: too short (should be at least 12 characters)")
            warnings.append("POSTGRES_PASSWORD too short")
        
        # Check REDIS_PASSWORD
        redis_password = os.getenv("REDIS_PASSWORD", "")
        if redis_password in ["", "redis", "password", "123456"]:
            self.logger.error("ENV", "REDIS_PASSWORD: using insecure default value")
            all_ok = False
        elif len(redis_password) < 12:
            self.logger.warning("ENV", "REDIS_PASSWORD: too short (should be at least 12 characters)")
            warnings.append("REDIS_PASSWORD too short")
        
        # Check JWT_SECRET_KEY
        jwt_secret = os.getenv("JWT_SECRET_KEY", "")
        if jwt_secret in ["", "secret", "key", "your-secret-key"]:
            self.logger.error("ENV", "JWT_SECRET_KEY: using insecure default value")
            all_ok = False
        elif len(jwt_secret) < 32:
            self.logger.error("ENV", "JWT_SECRET_KEY: too short (should be at least 32 characters)")
            all_ok = False
        
        # Check ALLOWED_ORIGINS
        allowed_origins = os.getenv("ALLOWED_ORIGINS", "")
        if not allowed_origins:
            self.logger.error("ENV", "ALLOWED_ORIGINS: not set")
            all_ok = False
        elif "*" in allowed_origins:
            self.logger.warning("ENV", "ALLOWED_ORIGINS: contains wildcard (*) - not recommended for production")
            warnings.append("ALLOWED_ORIGINS contains wildcard")
        
        if not warnings:
            self.logger.success("ENV", "All variables are secure ✓")
        
        return all_ok
