# =============================================================================
# Flutter APK 构建脚本（自动增加构建号）- Windows PowerShell 版本
# =============================================================================
# 用法:
#   .\scripts\build.ps1              # 构建 release APK，自动增加构建号
#   .\scripts\build.ps1 -NoBump      # 构建但不增加构建号
#   .\scripts\build.ps1 -SetBuild 100 # 设置指定构建号
# =============================================================================

param(
    [switch]$NoBump,
    [int]$SetBuild = 0
)

$ErrorActionPreference = "Stop"

# 获取脚本目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectDir = Split-Path -Parent $ScriptDir
$PubspecFile = Join-Path $ProjectDir "pubspec.yaml"

function Write-Info { param($msg) Write-Host "[INFO] $msg" -ForegroundColor Blue }
function Write-Success { param($msg) Write-Host "[OK] $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host "[WARN] $msg" -ForegroundColor Yellow }

# 读取当前版本
function Get-CurrentVersion {
    $content = Get-Content $PubspecFile -Raw
    if ($content -match "version:\s*(.+)") {
        return $Matches[1].Trim()
    }
    return "1.0.0+1"
}

# 解析版本号
function Parse-Version {
    param($version)
    $parts = $version -split '\+'
    return @{
        Name = $parts[0]
        Build = [int]$parts[1]
    }
}

# 更新版本号
function Update-Version {
    param($newVersion)
    $content = Get-Content $PubspecFile -Raw
    $content = $content -replace "version:\s*.+", "version: $newVersion"
    Set-Content $PubspecFile $content -NoNewline
}

# 主函数
function Main {
    Set-Location $ProjectDir

    # 获取当前版本
    $currentVersion = Get-CurrentVersion
    $version = Parse-Version $currentVersion

    Write-Info "当前版本: $currentVersion"
    Write-Info "版本名: $($version.Name), 构建号: $($version.Build)"

    # 更新构建号
    $buildNumber = $version.Build

    if ($SetBuild -gt 0) {
        $buildNumber = $SetBuild
        Write-Info "设置构建号为: $buildNumber"
    } elseif (-not $NoBump) {
        $buildNumber = $buildNumber + 1
        Write-Info "自动增加构建号为: $buildNumber"
    }

    $newVersion = "$($version.Name)+$buildNumber"

    if ($currentVersion -ne $newVersion) {
        Update-Version $newVersion
        Write-Success "版本更新为: $newVersion"
    }

    # 清理并获取依赖
    Write-Info "获取依赖..."
    flutter pub get

    # 构建 APK
    Write-Info "构建 Release APK..."
    flutter build apk --release

    # 输出结果
    $apkPath = Join-Path $ProjectDir "build\app\outputs\flutter-apk\app-release.apk"
    if (Test-Path $apkPath) {
        $apkSize = (Get-Item $apkPath).Length / 1MB
        Write-Success "构建完成!"
        Write-Host ""
        Write-Host "APK 信息:"
        Write-Host "  版本: $newVersion"
        Write-Host "  路径: $apkPath"
        Write-Host "  大小: $([math]::Round($apkSize, 2)) MB"
        Write-Host ""

        # 复制到 publish 目录
        $publishDir = Join-Path $ProjectDir "publish"
        if (-not (Test-Path $publishDir)) {
            New-Item -ItemType Directory -Path $publishDir | Out-Null
        }
        $publishPath = Join-Path $publishDir "rwa-durian-$($version.Name)-$buildNumber.apk"
        Copy-Item $apkPath $publishPath
        Write-Success "已复制到: $publishPath"
    } else {
        Write-Warn "APK 文件未找到"
        exit 1
    }
}

Main
