import importlib.util
import subprocess
import sys
import os

def install_package_from_wheel(wheel_path, package_name):
    """
    Install a Python package from a wheel file
    """
    try:
        print(f"Installing {package_name} from {wheel_path}...")
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", wheel_path,
            "--no-index", "--no-deps", "--break-system-packages",
            "--no-warn-script-location", "--force-reinstall"
        ], capture_output=True, text=True, timeout=60)
        if result.returncode == 0:
            print(f"✓ {package_name} installed successfully")
            return True
        else:
            print(f"✗ Failed to install {package_name}: {result.stderr}")
            return False
    except Exception as e:
        print(f"✗ Error installing {package_name}: {e}")
        return False

def check_and_install_dependencies(required_packages, repository_path):
    """
    Check if required packages are installed and install them from local repository if needed
    """
    print("Checking and installing dependencies...")
    missing_packages = []
    for package_name, wheel_file in required_packages.items():
        try:
            spec = importlib.util.find_spec(package_name)
            if spec is not None:
                continue  # Already installed
            else:
                print(f"✗ {package_name} is not installed")
                missing_packages.append((package_name, wheel_file))
        except ImportError:
            print(f"✗ {package_name} is not installed")
            missing_packages.append((package_name, wheel_file))
        except Exception as e:
            print(f"✗ Error checking {package_name}: {e}")
            missing_packages.append((package_name, wheel_file))
    if missing_packages:
        print(f"\nInstalling {len(missing_packages)} missing packages...")
        for package_name, wheel_file in missing_packages:
            if wheel_file is None:
                print(f"No wheel file for {package_name}, please install manually if needed.")
                continue
            wheel_path = os.path.join(repository_path, wheel_file)
            if not os.path.exists(wheel_path):
                print(f"✗ Wheel file not found: {wheel_path}")
                continue
            install_package_from_wheel(wheel_path, package_name)
    print("Dependency check completed.\n")
