
$Command = 'help'
$Rest = @()
if ($args.Count -gt 0) {
    $Command = [string]$args[0]
    if ($args.Count -gt 1) {
        $Rest = @($args[1..($args.Count - 1)])
    }
}

$ErrorActionPreference = 'Stop'

$RepoRoot   = Split-Path -Parent $PSScriptRoot
$ScriptsDir = $PSScriptRoot
$PinnedMdkReleaseUrl = 'https://github.com/wang-bin/mdk-sdk/releases/download/v0.37.0'
Set-Location $RepoRoot
. (Join-Path $ScriptsDir 'version-common.ps1')

function Show-Help {
    @"
SM-Emby Unified Dev Entry

  scripts\dev.ps1 <subcommand> [args...]

Subcommands:
  run        Smart dev run -- prepare the pinned Windows MDK SDK and skip unchanged pub get
             pass-through args: -Device, -Force, -Offline, -RefreshFvpDeps, -FlutterArgs <flutter args>
  android    Android dev run -- 自动检测真机/模拟器
             pass-through args: -Device <id>, -Emulator <id>, -Force, -Offline, -FlutterArgs <flutter args>
  installer  Build .exe installer (alias of build-installer.ps1)
             pass-through args: -SkipFlutterBuild, -Version <x.y.z>
  build      Build Windows release with the project-pinned MDK SDK
  build-apk  Build Android arm64 release with the project-pinned MDK SDK
  gen        dart run build_runner build --delete-conflicting-outputs
  clean      flutter clean
  pub        flutter pub get
  analyze    flutter analyze
  doctor     flutter doctor -v
  help       This help

Examples:
  scripts\dev.ps1 run
  scripts\dev.ps1 run -Force -FlutterArgs --release
  scripts\dev.ps1 run -RefreshFvpDeps
  scripts\dev.ps1 android
  scripts\dev.ps1 android -Device 18fa8f58
  scripts\dev.ps1 android -Emulator Pixel_10_Pro_XL
  scripts\dev.ps1 installer
  scripts\dev.ps1 installer -SkipFlutterBuild
  scripts\dev.ps1 build
  scripts\dev.ps1 build-apk
  scripts\dev.ps1 gen
"@ | Write-Host
}

function Invoke-Sub([string]$ScriptName) {
    $path = Join-Path $ScriptsDir $ScriptName
    if (-not (Test-Path $path)) { throw "Script not found: $path" }
    & $path @args
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

function Invoke-Flutter([string[]]$Args) {
    Write-Host "[dev] flutter $($Args -join ' ')" -ForegroundColor Cyan
    & flutter @Args
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

function Prepare-PinnedFvpWindowsDependencies {
    Invoke-Flutter @('pub', 'get')

    $prepareScript = Join-Path $ScriptsDir 'prepare-fvp-windows-deps.ps1'
    & powershell -ExecutionPolicy Bypass -File $prepareScript
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to prepare pinned fvp Windows dependencies (exit $LASTEXITCODE)"
    }
}

function Prepare-PinnedFvpAndroidDependencies {
    $Env:FVP_DEPS_URL = $PinnedMdkReleaseUrl
    $Env:FVP_DEPS_LATEST = $null

    Invoke-Flutter @('pub', 'get')

    $prepareScript = Join-Path $ScriptsDir 'prepare_fvp_android_deps.dart'
    & dart $prepareScript --project-root $RepoRoot
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to prepare pinned fvp Android dependencies (exit $LASTEXITCODE)"
    }
}

switch ($Command.ToLower()) {
    'run'        { Invoke-Sub 'dev-run.ps1'         @Rest }
    'android'    { Invoke-Sub 'dev-android.ps1'    @Rest }
    'installer'  { Invoke-Sub 'build-installer.ps1' @Rest }
    'build'      {
        Prepare-PinnedFvpWindowsDependencies

        $appVersion = Get-SmPlayerCurrentVersion -Platform windows -ProjectRoot $RepoRoot
        Write-Host "[dev] App version: $appVersion (windows/pc line)" -ForegroundColor Cyan

        $flutterBuildArgs = @('build', 'windows', '--release')
        if ($Rest) { $flutterBuildArgs += $Rest }
        $flutterBuildArgs = Add-SmPlayerBuildName -Arguments $flutterBuildArgs -Version $appVersion
        $flutterBuildArgs = Add-SmPlayerVersionDartDefine -Arguments $flutterBuildArgs -Version $appVersion
        Invoke-Flutter $flutterBuildArgs
    }
    'build-apk'  {
        Prepare-PinnedFvpAndroidDependencies

        $appVersion = Get-SmPlayerCurrentVersion -Platform android -ProjectRoot $RepoRoot
        $buildNumber = ConvertTo-SmPlayerBuildNumber -Version $appVersion
        Write-Host "[dev] App version: $appVersion (android line), build number: $buildNumber" -ForegroundColor Cyan

        $flutterBuildArgs = @('build', 'apk', '--release', '--target-platform', 'android-arm64')
        if ($Rest) { $flutterBuildArgs += $Rest }
        $flutterBuildArgs = Add-SmPlayerBuildName -Arguments $flutterBuildArgs -Version $appVersion
        if (-not (Test-SmPlayerFlutterOptionPresent -Arguments $flutterBuildArgs -OptionName '--build-number')) {
            $flutterBuildArgs += @('--build-number', [string]$buildNumber)
        }
        $flutterBuildArgs = Add-SmPlayerVersionDartDefine -Arguments $flutterBuildArgs -Version $appVersion
        Invoke-Flutter $flutterBuildArgs
    }
    'gen'        {
        Write-Host '[dev] dart run build_runner build --delete-conflicting-outputs' -ForegroundColor Cyan
        & dart run build_runner build --delete-conflicting-outputs
        if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    }
    'clean'      { Invoke-Flutter @('clean') }
    'pub'        { Invoke-Flutter @('pub', 'get') }
    'analyze'    { Invoke-Flutter @('analyze') }
    'doctor'     { Invoke-Flutter @('doctor', '-v') }
    'help'       { Show-Help }
    '--help'     { Show-Help }
    '-h'         { Show-Help }
    default {
        Write-Host "Unknown subcommand: $Command" -ForegroundColor Red
        Write-Host ''
        Show-Help
        exit 1
    }
}
