param (
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$AllArgs
)
# 初始化变量
$packageArgs = @()
$flutterArgs = @()
$inFlutterArgs = $false

# 参数解析
foreach ($arg in $AllArgs) {
    if ($arg -eq "--args") {
        $inFlutterArgs = $true
        continue
    }

    if ($inFlutterArgs) {
        $flutterArgs += $arg
    } else {
        $packageArgs += $arg
    }
}


function Write-FilesToJson {
    param (
        [Parameter(Mandatory=$true)]
        [string]$TargetDir,        # 要扫描的目录

        [Parameter(Mandatory=$true)]
        [string]$OutputJsonPath    # 输出的 JSON 文件路径
    )

    if (-Not (Test-Path $TargetDir)) {
        throw "dir '$TargetDir' is not exists"
    }

    # 获取当前工作目录用于相对路径计算
    $basePath = Resolve-Path $TargetDir

    # 收集所有文件（递归）
    $files = Get-ChildItem -Path $TargetDir -File -Recurse | ForEach-Object {
        # 计算相对路径
        $relativePath = "assets\"+$_.FullName.Substring($basePath.Path.Length).TrimStart('\', '/')
        return $relativePath
    }

    # 转为 JSON 并保存
    $json = $files | ConvertTo-Json -Depth 10
    Set-Content -Path $OutputJsonPath -Value $json -Encoding UTF8

    Write-Host "save to: $OutputJsonPath"
}

function Invoke-AllScriptsInScriptFolder {
    param (
        [string[]]$packageArgs,
        [string[]]$flutterArgs
    )
    $scriptDir = Join-Path -Path (Get-Location) -ChildPath "script"
    if (-not (Test-Path $scriptDir)) {
        return
    }
    $scripts = Get-ChildItem -Path $scriptDir -Filter *.ps1 | Sort-Object Name
    foreach ($script in $scripts) {
        Write-Host "`nruning script at: $($script.Name)"
        & $script.FullName `
            --packageArgs @($packageArgs) `
            --flutterArgs @($flutterArgs)
        if ($LASTEXITCODE -ne 0) {
            Write-Host " script $($script.Name) is failed , because return is not 0"
        }
    }
}

for ($i = 0; $i -lt $packageArgs.Count; $i++) {
    $arg = $packageArgs[$i]
    if ($arg.StartsWith("--assetsinfo")) {
        $value = ""
        if ($arg.Contains('=')) {
            $value = $arg -replace '^--assetsinfo=', ''    
        }
        if ([string]::IsNullOrEmpty($value)) {
            $value = "assets/file.json"
        }
        Write-FilesToJson -TargetDir "assets" -OutputJsonPath $value
    }
}
Invoke-AllScriptsInScriptFolder -packageArgs $packageArgs -flutterArgs $flutterArgs
# 构造 flutter 命令
$flutterCommand = "flutter"
$flutterArgsStr = $flutterArgs -join " "
Write-Host "`nruning: flutter $flutterArgsStr`n"
if ($flutterArgs.Count -gt 0) {
    # 调用 flutter 命令
    & $flutterCommand @flutterArgs
}