[CmdletBinding()]
param(
    [ValidateSet('Auto', 'Disable', 'Enable', 'Keep')]
    [string]$WebViewMultiprocess = 'Auto',

    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$FlutterArgs
)

$ErrorActionPreference = 'Stop'

$projectRoot = Split-Path -Parent $PSScriptRoot
$localPropertiesPath = Join-Path $projectRoot 'android\local.properties'
$packageName = 'com.yuanxuan.webshell.web_android_shell'

function Get-LocalPropertyValue {
    param(
        [string]$Path,
        [string]$Name
    )

    if (-not (Test-Path $Path)) {
        return $null
    }

    $escapedName = [regex]::Escape($Name)
    foreach ($line in Get-Content $Path) {
        if ($line -match "^$escapedName=(.+)$") {
            return $matches[1].Trim() -replace '\\\\', '\'
        }
    }

    return $null
}

function Get-DeviceIdFromArgs {
    param([string[]]$ArgsToScan)

    for ($index = 0; $index -lt $ArgsToScan.Length; $index += 1) {
        $arg = $ArgsToScan[$index]
        if ($arg -eq '-d' -or $arg -eq '--device-id') {
            if ($index + 1 -lt $ArgsToScan.Length) {
                return $ArgsToScan[$index + 1]
            }
        }

        if ($arg.StartsWith('--device-id=')) {
            return $arg.Substring('--device-id='.Length)
        }
    }

    return $null
}

function Get-DeviceModel {
    param(
        [string]$AdbPath,
        [string[]]$AdbArgsPrefix
    )

    return ((& $AdbPath @AdbArgsPrefix shell getprop ro.product.model) | Out-String).Trim()
}

function Get-WebViewUpdateState {
    param(
        [string]$AdbPath,
        [string[]]$AdbArgsPrefix
    )

    return (& $AdbPath @AdbArgsPrefix shell dumpsys webviewupdate | Out-String)
}

function Get-WebViewInfo {
    param(
        [string]$AdbPath,
        [string[]]$AdbArgsPrefix
    )

    $state = Get-WebViewUpdateState -AdbPath $AdbPath -AdbArgsPrefix $AdbArgsPrefix
    $multiprocessEnabled = $state -match 'Multiprocess enabled:\s+true'
    $versionName = $null

    if ($state -match 'Current WebView package \(name, version\): \([^\),]+,\s*([^\)]+)\)') {
        $versionName = $matches[1].Trim()
    }

    $majorVersion = $null
    if ($versionName) {
        $majorToken = $versionName.Split('.')[0]
        $parsedMajor = 0
        if ([int]::TryParse($majorToken, [ref]$parsedMajor)) {
            $majorVersion = $parsedMajor
        }
    }

    return @{
        MultiprocessEnabled = $multiprocessEnabled
        VersionName = $versionName
        MajorVersion = $majorVersion
        RawState = $state
    }
}

function Set-WebViewMultiprocessState {
    param(
        [string]$AdbPath,
        [string[]]$AdbArgsPrefix,
        [bool]$Enabled
    )

    $command = if ($Enabled) { 'enable-multiprocess' } else { 'disable-multiprocess' }
    & $AdbPath @AdbArgsPrefix shell cmd webviewupdate $command | Out-Host
    Start-Sleep -Seconds 1
}

$sdkDir = Get-LocalPropertyValue -Path $localPropertiesPath -Name 'sdk.dir'
$adbPath = $null

if ($sdkDir) {
    $candidate = Join-Path $sdkDir 'platform-tools\adb.exe'
    if (Test-Path $candidate) {
        $adbPath = $candidate
    }
}

if (-not $adbPath) {
    $adbCommand = Get-Command adb.exe -ErrorAction SilentlyContinue
    if ($adbCommand) {
        $adbPath = $adbCommand.Source
    }
}

if (-not $adbPath) {
    throw "未找到 adb.exe，请检查 android/local.properties 中的 sdk.dir。"
}

$deviceId = Get-DeviceIdFromArgs -ArgsToScan $FlutterArgs
$adbArgsPrefix = @()

if ($deviceId) {
    $adbArgsPrefix = @('-s', $deviceId)
}

Write-Host "Using adb: $adbPath"
if ($deviceId) {
    Write-Host "Target device: $deviceId"
}

& $adbPath @adbArgsPrefix start-server | Out-Null

$deviceModel = Get-DeviceModel -AdbPath $adbPath -AdbArgsPrefix $adbArgsPrefix
$webViewInfo = Get-WebViewInfo -AdbPath $adbPath -AdbArgsPrefix $adbArgsPrefix

Write-Host "Device model: $deviceModel"
if ($webViewInfo.VersionName) {
    Write-Host "System WebView: $($webViewInfo.VersionName)"
}
Write-Host "WebView multiprocess enabled: $($webViewInfo.MultiprocessEnabled)"

$shouldDisableMultiprocess = $false
switch ($WebViewMultiprocess) {
    'Disable' {
        $shouldDisableMultiprocess = $true
    }
    'Auto' {
        $shouldDisableMultiprocess =
            $deviceModel -eq 'F136A' -or
            ($webViewInfo.MajorVersion -ne $null -and $webViewInfo.MajorVersion -le 101)
    }
}

if ($shouldDisableMultiprocess -and $webViewInfo.MultiprocessEnabled) {
    Write-Host "Disabling Android WebView multiprocess for compatibility..."
    Set-WebViewMultiprocessState -AdbPath $adbPath -AdbArgsPrefix $adbArgsPrefix -Enabled:$false
} elseif ($WebViewMultiprocess -eq 'Enable' -and -not $webViewInfo.MultiprocessEnabled) {
    Write-Host "Re-enabling Android WebView multiprocess..."
    Set-WebViewMultiprocessState -AdbPath $adbPath -AdbArgsPrefix $adbArgsPrefix -Enabled:$true
}

Write-Host "Force-stopping previous app process: $packageName"
& $adbPath @adbArgsPrefix shell am force-stop $packageName | Out-Null

Start-Sleep -Milliseconds 800

Write-Host "Starting flutter run..."
& flutter run @FlutterArgs
exit $LASTEXITCODE
