# ╔═══════════════════════════════════════════════════════════════════════════════╗
# ║                        🚨 CRITICAL WARNING 🚨                                ║
# ║                     AUTOGENERATED! DO NOT EDIT!                              ║
# ║                                                                               ║
# ║  This file is AUTOMATICALLY GENERATED from source modules.                   ║
# ║  ANY CHANGES MADE HERE WILL BE LOST when modules are re-exported!            ║
# ║                                                                               ║
# ║  ✅ TO EDIT: modules/source/_guards/_import_guard_dev.py                     ║
# ║  ✅ TO EXPORT: Run 'tito module complete <module_name>'                      ║
# ║                                                                               ║
# ║  🛡️ STUDENT PROTECTION: This file contains critical fixes for Variable/      ║
# ║     Tensor compatibility. Editing it directly WILL break CIFAR-10 training.  ║
# ║                                                                               ║
# ║  🎓 LEARNING TIP: Work in modules/source/ - that's where real development    ║
# ║     happens! The tinytorch/ directory is just the compiled output.           ║
# ╚═══════════════════════════════════════════════════════════════════════════════╝

"""
🛡️ TinyTorch Import Guard System

Industry-standard protection mechanism that intercepts imports and validates
critical functionality before students can use potentially broken code.

This is similar to:
- React's development warnings
- Django's system checks  
- Webpack's build validation
- Rust's compile-time checks
"""

import sys
import os
import warnings
import hashlib
from typing import Dict, Any, Optional
from pathlib import Path


class TinyTorchImportGuard:
    """
    🛡️ **INDUSTRY-STANDARD PROTECTION**: Import guard that validates core functionality.
    
    This class intercepts imports of critical TinyTorch modules and runs validation
    checks to ensure students haven't accidentally broken core functionality.
    
    **Industry Examples:**
    - Node.js: Checks for compatible module versions on import
    - Python Django: Runs system checks before serving requests  
    - React: Shows development warnings for common mistakes
    - Webpack: Validates dependencies during build
    """
    
    def __init__(self):
        self.validated_modules = set()
        self.file_hashes = {}
        self.critical_modules = {
            'tinytorch.core.tensor',
            'tinytorch.core.autograd', 
            'tinytorch.core.layers',
            'tinytorch.core.activations',
            'tinytorch.core.training',
            'tinytorch.core.optimizers'
        }
        
    def compute_file_hash(self, filepath: str) -> str:
        """Compute hash of file to detect modifications."""
        try:
            with open(filepath, 'rb') as f:
                content = f.read()
                return hashlib.md5(content).hexdigest()
        except (IOError, OSError):
            return ""
    
    def check_file_integrity(self, module_name: str) -> bool:
        """
        🛡️ Check if core files have been modified unexpectedly.
        
        This detects when students edit generated files directly,
        which breaks the Variable/Tensor compatibility fixes.
        """
        if not module_name.startswith('tinytorch.core.'):
            return True
            
        # Convert module name to file path
        module_file = module_name.replace('.', '/') + '.py'
        file_path = Path(module_file)
        
        if not file_path.exists():
            return True
        
        # Check if file has our protection header
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                first_lines = f.read(500)
                if "AUTOGENERATED! DO NOT EDIT!" not in first_lines:
                    warnings.warn(
                        f"🚨 {module_name} missing auto-generated warning header. "
                        f"File may have been manually edited.",
                        UserWarning
                    )
                    return False
        except (IOError, OSError):
            pass
            
        return True
    
    def validate_critical_functionality(self, module_name: str) -> bool:
        """
        🛡️ Validate that critical functionality works after import.
        
        This catches when students break Variable/Tensor compatibility.
        """
        if module_name == 'tinytorch.core.layers':
            try:
                # Quick test of matmul with Variables
                from tinytorch.core.tensor import Tensor
                from tinytorch.core.autograd import Variable
                from tinytorch.core.layers import matmul
                
                a = Variable(Tensor([[1, 2]]), requires_grad=True)
                b = Variable(Tensor([[3], [4]]), requires_grad=True)
                result = matmul(a, b)
                
                if not hasattr(result, 'requires_grad'):
                    raise ValueError("matmul doesn't handle Variables correctly")
                    
            except Exception as e:
                warnings.warn(
                    f"🚨 CRITICAL: tinytorch.core.layers functionality broken! "
                    f"Error: {e}. This will prevent CIFAR-10 training.",
                    UserWarning
                )
                return False
                
        elif module_name == 'tinytorch.core.activations':
            try:
                # Quick test of ReLU with Variables
                from tinytorch.core.tensor import Tensor
                from tinytorch.core.autograd import Variable
                from tinytorch.core.activations import ReLU
                
                relu = ReLU()
                x = Variable(Tensor([[-1, 1]]), requires_grad=True)
                result = relu(x)
                
                if not hasattr(result, 'requires_grad'):
                    raise ValueError("ReLU doesn't handle Variables correctly")
                    
            except Exception as e:
                warnings.warn(
                    f"🚨 CRITICAL: tinytorch.core.activations functionality broken! "
                    f"Error: {e}. This will prevent CIFAR-10 training.",
                    UserWarning
                )
                return False
        
        return True
    
    def guard_import(self, module_name: str) -> bool:
        """
        🛡️ **MAIN GUARD FUNCTION**: Validate module on import.
        
        Args:
            module_name: Name of module being imported
            
        Returns:
            bool: True if module is safe to use
        """
        # Skip if already validated
        if module_name in self.validated_modules:
            return True
            
        # Skip non-critical modules
        if module_name not in self.critical_modules:
            return True
        
        # Run protection checks
        integrity_ok = self.check_file_integrity(module_name)
        functionality_ok = self.validate_critical_functionality(module_name)
        
        if integrity_ok and functionality_ok:
            self.validated_modules.add(module_name)
            return True
        else:
            # Don't block import, just warn
            warnings.warn(
                f"🛡️ TinyTorch protection detected issues with {module_name}. "
                f"Check if you've accidentally edited generated files.",
                UserWarning
            )
            return False


# Global import guard instance
_import_guard = TinyTorchImportGuard()


class TinyTorchImportHook:
    """
    🛡️ **INDUSTRY-STANDARD TECHNIQUE**: Python import hook.
    
    This integrates with Python's import system to automatically
    validate modules as they're imported. Similar to:
    - Django's app loading system
    - Pytest's plugin discovery
    - Setuptools entry points
    """
    
    def find_spec(self, name, path, target=None):
        """Hook into Python's import system.""" 
        if name.startswith('tinytorch.core.'):
            # Run validation check
            _import_guard.guard_import(name)
        
        # Don't interfere with actual import
        return None
    
    def find_module(self, name, path=None):
        """Legacy import hook interface."""
        if name.startswith('tinytorch.core.'):
            _import_guard.guard_import(name)
        return None


def install_import_protection():
    """
    🛡️ Install the import protection system.
    
    This is called automatically when the module is imported.
    Students don't need to do anything - protection is automatic.
    """
    # Install our import hook
    if not any(isinstance(hook, TinyTorchImportHook) for hook in sys.meta_path):
        sys.meta_path.insert(0, TinyTorchImportHook())


def uninstall_import_protection():
    """🛡️ Remove import protection (for testing/debugging)."""
    sys.meta_path[:] = [hook for hook in sys.meta_path 
                        if not isinstance(hook, TinyTorchImportHook)]


def manual_validation_check():
    """
    🛡️ **MANUAL VALIDATION**: Run protection checks explicitly.
    
    Students/instructors can call this to check system health:
    
    ```python
    from tinytorch.core._import_guard import manual_validation_check
    manual_validation_check()
    ```
    """
    print("🛡️ Running TinyTorch Manual Validation Check...")
    print("=" * 60)
    
    for module_name in _import_guard.critical_modules:
        try:
            integrity = _import_guard.check_file_integrity(module_name)
            functionality = _import_guard.validate_critical_functionality(module_name)
            
            status = "✅ PASS" if (integrity and functionality) else "❌ FAIL"
            print(f"{status} {module_name}")
            
            if not (integrity and functionality):
                print(f"    ⚠️  Issues detected - check for manual edits")
                
        except Exception as e:
            print(f"❌ FAIL {module_name} - Error: {e}")
    
    print("=" * 60)
    print("🛡️ Validation complete. Any failures indicate protection issues.")


# 🛡️ AUTO-INSTALL: Protection activates when this module is imported
# This ensures students are automatically protected without any setup
install_import_protection()