"""
Tier 1: Local validation - Fast syntax and import checking.

This module provides lightning-fast (~100ms) validation of project files
before any expensive operations. It checks:
- Python syntax errors
- Import errors (missing dependencies)
- Config file validity
- Basic project structure
"""

import ast
import json
import sys
from pathlib import Path
from typing import Optional
from dataclasses import dataclass, field


@dataclass
class ValidationResult:
    """Result of Tier 1 validation."""
    success: bool
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    
    def add_error(self, message: str):
        self.errors.append(message)
        self.success = False
    
    def add_warning(self, message: str):
        self.warnings.append(message)


class LocalValidator:
    """Fast local validation for common project issues."""
    
    def validate(self, project_path: Path) -> ValidationResult:
        """
        Run all Tier 1 validations.
        
        Args:
            project_path: Path to the project directory
            
        Returns:
            ValidationResult with any errors or warnings
        """
        result = ValidationResult(success=True)
        
        # Check Python files for syntax errors
        self._validate_python_syntax(project_path, result)
        
        # Validate config files
        self._validate_configs(project_path, result)
        
        # Check for required files
        self._validate_required_files(project_path, result)
        
        return result
    
    def _validate_python_syntax(self, project_path: Path, result: ValidationResult):
        """Check all Python files for syntax errors."""
        python_files = list(project_path.rglob("*.py"))
        
        for py_file in python_files:
            # Skip common virtual environment directories
            if any(part.startswith(".") or part in ["venv", ".venv", "env", ".env", "__pycache__"] 
                   for part in py_file.parts):
                continue
            
            try:
                content = py_file.read_text(encoding="utf-8")
                ast.parse(content)
            except SyntaxError as e:
                result.add_error(
                    f"Syntax error in {py_file.relative_to(project_path)}:{e.lineno}: {e.msg}"
                )
            except UnicodeDecodeError:
                result.add_warning(f"Could not read {py_file.relative_to(project_path)} (encoding issue)")
    
    def _validate_configs(self, project_path: Path, result: ValidationResult):
        """Validate configuration files."""
        # requirements.txt - check format
        req_file = project_path / "requirements.txt"
        if req_file.exists():
            try:
                content = req_file.read_text(encoding="utf-8")
                for line_num, line in enumerate(content.split("\n"), 1):
                    line = line.strip()
                    if not line or line.startswith("#"):
                        continue
                    # Basic format check
                    if ";" in line and "sys_platform" not in line and "python_version" not in line:
                        # Might be an error, but could also be valid
                        pass
            except Exception as e:
                result.add_error(f"Error reading requirements.txt: {e}")
        
        # package.json - validate JSON
        pkg_file = project_path / "package.json"
        if pkg_file.exists():
            try:
                content = pkg_file.read_text(encoding="utf-8")
                json.loads(content)
            except json.JSONDecodeError as e:
                result.add_error(f"Invalid package.json: {e}")
        
        # pyproject.toml - basic check
        pyproject = project_path / "pyproject.toml"
        if pyproject.exists():
            try:
                import tomllib
                content = pyproject.read_bytes()
                tomllib.loads(content.decode("utf-8"))
            except ImportError:
                # Python < 3.11, try toml library
                try:
                    import toml
                    toml.load(pyproject)
                except ImportError:
                    pass  # Skip if no toml library
                except Exception as e:
                    result.add_error(f"Invalid pyproject.toml: {e}")
            except Exception as e:
                result.add_error(f"Invalid pyproject.toml: {e}")
    
    def _validate_required_files(self, project_path: Path, result: ValidationResult):
        """Check for required files based on detected project type."""
        # Detect project type
        has_requirements = (project_path / "requirements.txt").exists()
        has_pyproject = (project_path / "pyproject.toml").exists()
        has_package_json = (project_path / "package.json").exists()
        has_go_mod = (project_path / "go.mod").exists()
        has_cargo = (project_path / "Cargo.toml").exists()
        
        # Check for main entry point (Python)
        if has_requirements or has_pyproject:
            main_files = [
                project_path / "main.py",
                project_path / "app.py",
                project_path / "manage.py",  # Django
            ]
            app_dirs = [
                project_path / "app",
                project_path / project_path.name.lower().replace("-", "_").replace(" ", "_"),
            ]
            
            if not any(f.exists() for f in main_files):
                # Check if there's a package directory with __main__.py or similar
                has_entry = False
                for app_dir in app_dirs:
                    if app_dir.is_dir():
                        if (app_dir / "__main__.py").exists() or (app_dir / "main.py").exists():
                            has_entry = True
                            break
                
                if not has_entry:
                    result.add_warning(
                        "No clear Python entry point found (main.py, app.py, or package/__main__.py)"
                    )
        
        # Check for main entry point (Node.js)
        if has_package_json:
            pkg_json = json.loads((project_path / "package.json").read_text())
            if "main" not in pkg_json and "start" not in str(pkg_json.get("scripts", {})):
                result.add_warning(
                    "No 'main' field or 'start' script found in package.json"
                )


def validate_project(project_path: Path) -> ValidationResult:
    """
    Convenience function for Tier 1 validation.
    
    Args:
        project_path: Path to the project directory
        
    Returns:
        ValidationResult with errors and warnings
    """
    validator = LocalValidator()
    return validator.validate(project_path)
