chromedriver.psm1

# Module: chromedriver.psm1

# Path Helpers
function Get-ChromePath {
    $paths = @(
        "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
        "$env:ProgramFiles(x86)\Google\Chrome\Application\chrome.exe",
        "$env:LOCALAPPDATA\Google\Chrome\Application\chrome.exe"
    )
    foreach ($path in $paths) {
        if (Test-Path $path) { return $path }
    }
    return $null
}

function Add-ChromeToPath {
    param([string]$ChromePath)
    $dir = Split-Path $ChromePath
    $inPath = $env:PATH -split ';' | Where-Object { $_ -eq $dir }

    if (-not $inPath) {
        $env:PATH += ";$dir"
        Write-Host "🔧 Chrome path added to session PATH: $dir"
    } else {
        Write-Host "✔️ Chrome path already in session PATH: $dir"
    }

    $userPath = [Environment]::GetEnvironmentVariable("Path", "User") -split ';'
    if ($userPath -notcontains $dir) {
        $newPath = ([string]::Join(';', $userPath + $dir))
        [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
        Write-Host "📌 Chrome path added to user environment PATH: $dir"
    } else {
        Write-Host "✔️ Chrome path already in user environment PATH: $dir"
    }
}

function Get-ChromeVersion {
    param([string]$ChromePath)
    (Get-Item $ChromePath).VersionInfo.ProductVersion
}

function Get-ChromeDriverUrl {
    param([string]$Version)
    $base = "https://storage.googleapis.com/chrome-for-testing-public/$Version"
    return "$base/win64/chromedriver-win64.zip"
}

function Install-ChromeDriver {
    param([string]$Version)

    $url = Get-ChromeDriverUrl -Version $Version
    $zipPath = Join-Path $env:TEMP "chromedriver.zip"
    Write-Host "⬇️ Downloading ChromeDriver from $url"
    Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing

    $extractPath = Join-Path $env:TEMP "chromedriver_extracted"
    Write-Host "📂 Extracting to $extractPath"
    New-Item -ItemType Directory -Path $extractPath -Force | Out-Null
    Expand-Archive -Path $zipPath -OutputPath $extractPath -Force

    $driverPath = Get-ChildItem "$extractPath\**\chromedriver.exe" -Recurse | Select-Object -First 1
    Write-Host "🔎 Found driverPath: $($driverPath.FullName)"

    $seleniumDriverTarget = "$env:USERPROFILE\Documents\PowerShell\Modules\Selenium\3.0.1\assemblies\chromedriver.exe"
    if (-not (Test-Path (Split-Path $seleniumDriverTarget))) {
        New-Item -ItemType Directory -Path (Split-Path $seleniumDriverTarget) -Force | Out-Null
    }
    Write-Host "🔎 Will copy to: $seleniumDriverTarget"
    Copy-Item $driverPath.FullName $seleniumDriverTarget -Force
    Write-Host "✅ Replaced Selenium's chromedriver.exe"
}

function Install-Chrome {
    $chromeUrl = "https://dl.google.com/chrome/install/latest/chrome_installer.exe"
    $installer = Join-Path $env:TEMP "chrome_installer.exe"
    Invoke-WebRequest -Uri $chromeUrl -OutFile $installer -UseBasicParsing
    Start-Process -FilePath $installer -ArgumentList "/silent /install" -Wait
    Remove-Item $installer
}

function Install-SeleniumModule {
    if (-not (Get-Module -ListAvailable Selenium)) {
        Install-Module Selenium -Scope CurrentUser -Force
    }
}

function Initialize-ChromeDriver {
    $chrome = Get-ChromePath
    if (-not $chrome) {
        Write-Warning "Chrome not found. Installing..."
        Install-Chrome
        $chrome = Get-ChromePath
    }
    if (-not $chrome) {
        throw "❌ Chrome installation failed."
    }

    Add-ChromeToPath -ChromePath $chrome
    $version = Get-ChromeVersion -ChromePath $chrome

    Write-Host "🔍 Detected Chrome version: $version"

    Install-ChromeDriver -Version $version
    Install-SeleniumModule
    Write-Host "✅ Chrome + ChromeDriver setup complete."
}

function Test-ChromeSelenium {
    param(
        [switch]$Headless
    )

    Import-Module Selenium
    $args = if ($Headless) { "--headless --disable-gpu" } else { "" }
    $driver = Start-SeChrome -Arguments $args
    $driver.Navigate().GoToUrl("https://example.com")
    Start-Sleep -Seconds 5
    $title = $driver.Title
    $driver.Quit()

    if ($title -eq "Example Domain") {
        Write-Host "✅ Selenium test passed! Page loaded successfully."
    } else {
        Write-Warning "⚠️ Unexpected page title: $title"
    }
}