"""
Frontend checks module
"""
import os
from typing import List
from tests.utils.logger import Logger
from tests.utils.http_utils import HTTPUtils


class FrontendChecks:
    """Check frontend accessibility"""
    
    def __init__(self, logger: Logger, project_dir: str, version: str = "unknown"):
        self.logger = logger
        self.version = version
        self.project_dir = project_dir
        self.http_utils = HTTPUtils(logger)
        self.urls = self._get_frontend_urls()
    
    def _get_frontend_urls(self) -> List[str]:
        """Get frontend URLs from .env file"""
        urls = []
        
        # Always check localhost
        urls.append("http://localhost:3000")
        
        # Try to read DOMAIN from .env
        env_file = os.path.join(self.project_dir, ".env")
        if os.path.exists(env_file):
            try:
                with open(env_file, 'r') as f:
                    for line in f:
                        line = line.strip()
                        if line.startswith('DOMAIN='):
                            domain = line.split('=', 1)[1].strip()
                            if domain and domain != 'localhost':
                                # Add both HTTP and HTTPS
                                urls.append(f"http://{domain}")
                                urls.append(f"https://{domain}")
                            break
            except Exception as e:
                self.logger.warning("FRONTEND", f"Failed to read .env: {e}")
        
        return urls
    
    def run_all_checks(self) -> bool:
        """Run all frontend checks"""
        self.logger.subheader(f"Frontend Checks (v{self.version})")
        
        # Check frontend URL accessibility for all configured URLs
        if not self._check_frontend_accessible():
            return False
        
        # Check static files
        if not self._check_static_files():
            return False
        
        # Check frontend container health
        if not self._check_frontend_health():
            return False
        
        # Check for frontend calls to non-existent API endpoints
        if not self._check_nonexistent_api_endpoints():
            return False
        
        self.logger.success("FRONTEND", "All frontend checks passed")
        return True
    
    def _check_frontend_accessible(self) -> bool:
        """Check if frontend URLs are accessible"""
        self.logger.info("FRONTEND", f"Checking frontend accessibility for {len(self.urls)} URL(s)...")
        
        any_accessible = False
        for url in self.urls:
            self.logger.info("FRONTEND", f"Checking {url}...")
            if self.http_utils.check_url_accessible(url):
                self.logger.success("FRONTEND", f"Frontend accessible at {url}")
                any_accessible = True
            else:
                self.logger.info("FRONTEND", f"Frontend not accessible at {url}")
        
        if any_accessible:
            return True
        else:
            self.logger.info("FRONTEND", "No frontend URL accessible - container might not be running")
            return True  # Not critical for backend tests
    
    def _check_static_files(self) -> bool:
        """Check if static files are loading"""
        self.logger.info("FRONTEND", "Checking static file loading...")
        
        # Use the first accessible URL
        accessible_url = None
        for url in self.urls:
            if self.http_utils.check_url_accessible(url):
                accessible_url = url
                break
        
        if not accessible_url:
            self.logger.info("FRONTEND", "No accessible frontend URL found")
            return True  # Not critical
        
        # Try to access common static file paths
        static_paths = [
            "/assets/",
            "/index.html",
        ]
        
        for path in static_paths:
            url = f"{accessible_url}{path}"
            if self.http_utils.check_url_accessible(url):
                self.logger.success("FRONTEND", f"Static file accessible: {path}")
                return True
        
        self.logger.info("FRONTEND", "Could not verify static files (frontend might not be fully loaded)")
        return True  # Not critical
    
    def _check_frontend_health(self) -> bool:
        """Check frontend container health using docker exec"""
        self.logger.info("FRONTEND", "Checking frontend container health...")
        
        try:
            import subprocess
            # Check if frontend container is running
            result = subprocess.run(
                ["docker", "inspect", "-f", "{{.State.Status}}", "streama2026-frontend"],
                capture_output=True,
                text=True,
                timeout=10
            )
            
            if result.returncode == 0:
                status = result.stdout.strip()
                if status == "running":
                    self.logger.success("FRONTEND", f"Frontend container status: {status}")
                    return True
                else:
                    self.logger.info("FRONTEND", f"Frontend container status: {status}")
                    return True  # Not critical
            else:
                self.logger.info("FRONTEND", "Could not check frontend container status")
                return True  # Not critical
        except Exception as e:
            self.logger.info("FRONTEND", f"Frontend health check failed: {e}")
            return True  # Not critical
    
    def _check_nonexistent_api_endpoints(self) -> bool:
        """Check if frontend attempts to access non-existent API endpoints"""
        self.logger.info("FRONTEND", "Checking for frontend calls to non-existent API endpoints...")
        
        # Use compare_apis() for consistency with API Endpoint Analysis
        try:
            from tests.utils.api_analyzer import APIAnalyzer
            api_analyzer = APIAnalyzer(self.project_dir, version=self.version)
            
            api_differences = api_analyzer.compare_apis()
            
            if api_differences["missing_backend_endpoints"]:
                self.logger.warning("FRONTEND", f"Found {len(api_differences['missing_backend_endpoints'])} missing backend endpoints")
                for endpoint in api_differences["missing_backend_endpoints"]:
                    self.logger.info("FRONTEND", f"  - {endpoint['method']} {endpoint['path']} called from {endpoint['file']}:{endpoint['line']}")
                return False
            else:
                self.logger.success("FRONTEND", "No frontend calls to non-existent API endpoints")
                return True
        except Exception as e:
            self.logger.warning("FRONTEND", f"Failed to check for non-existent API endpoints: {e}")
            return True  # Not critical
