param(
    [string]$Slug = 'ikar-android',
    [string]$Name,
    [string]$Summary = 'Standalone Android client for Ikar on Kotlin and Jetpack Compose.',
    [string]$Description = 'Standalone Android client on Kotlin and Jetpack Compose, prepared as a staged replacement for the current MAUI client.',
    [string]$Version,
    [string]$Channel = 'stable',
    [string]$Platform = 'android',
    [string]$Notes,
    [string]$RepositoryUrl = 'https://git.kusoft.xyz/sevenhill/Massenger.git',
    [string]$HomepageUrl = 'https://ikar.kusoft.xyz',
    [switch]$Unlisted,
    [switch]$SkipSigningInitialization
)

$ErrorActionPreference = 'Stop'

function Require-Tool([string]$Path, [string]$Label) {
    if (-not (Test-Path $Path)) {
        throw "$Label was not found: $Path"
    }
}

function Get-ApkBadgingValue([string]$BadgingText, [string]$Pattern) {
    $match = [regex]::Match($BadgingText, $Pattern, [System.Text.RegularExpressions.RegexOptions]::Multiline)
    if (-not $match.Success) {
        return $null
    }
    return $match.Groups[1].Value
}

function Resolve-ArgusPlatform([string[]]$NativeCodes) {
    $normalized = $NativeCodes | Where-Object { $_ } | ForEach-Object { $_.Trim().ToLowerInvariant() }
    $allUniversalAbis = @('arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64')
    if (@($allUniversalAbis | Where-Object { $normalized -contains $_ }).Count -eq $allUniversalAbis.Count) {
        return 'android-universal'
    }
    if ($normalized -contains 'arm64-v8a') {
        return 'android-arm64'
    }
    if ($normalized -contains 'armeabi-v7a') {
        return 'android-armv7'
    }
    if ($normalized -contains 'x86_64') {
        return 'android-x86_64'
    }
    if ($normalized -contains 'x86') {
        return 'android-x86'
    }
    return 'android'
}

$repoRoot = Split-Path -Parent $PSScriptRoot
Set-Location $repoRoot

$javaHome = if ($env:JAVA_HOME) { $env:JAVA_HOME } else { 'C:\Program Files\Android\openjdk\jdk-21.0.8' }
$androidHome = if ($env:ANDROID_HOME) { $env:ANDROID_HOME } else { 'C:\Users\seven\AppData\Local\Android\Sdk' }
$env:JAVA_HOME = $javaHome
$env:ANDROID_HOME = $androidHome

$gradlePath = Join-Path $repoRoot 'gradlew.bat'
$aaptPath = Join-Path $androidHome 'build-tools\36.1.0\aapt.exe'
$apksignerPath = Join-Path $androidHome 'build-tools\36.1.0\apksigner.bat'
$signingPropertiesPath = Join-Path $repoRoot 'argus-signing.local.properties'
$signingInitScript = Join-Path $PSScriptRoot 'new-argus-upload-keystore.ps1'

Require-Tool $gradlePath 'Gradle wrapper'
Require-Tool $aaptPath 'aapt'
Require-Tool $apksignerPath 'apksigner'
Require-Tool $signingInitScript 'Argus signing init script'

if (-not (Test-Path $signingPropertiesPath)) {
    if ($SkipSigningInitialization) {
        throw "Signing properties were not found: $signingPropertiesPath"
    }
    & $signingInitScript
    if ($LASTEXITCODE -ne 0) {
        throw "Signing initialization failed with exit code $LASTEXITCODE."
    }
}

& $gradlePath :app:assembleRelease --console=plain
if ($LASTEXITCODE -ne 0) {
    throw "Gradle release build failed with exit code $LASTEXITCODE."
}

$outputMetadataPath = Join-Path $repoRoot 'app\build\outputs\apk\release\output-metadata.json'
if (-not (Test-Path $outputMetadataPath)) {
    throw "Release output metadata was not found: $outputMetadataPath"
}

$outputMetadata = Get-Content $outputMetadataPath -Raw | ConvertFrom-Json
$outputFile = $outputMetadata.elements[0].outputFile
$releaseApkPath = Join-Path $repoRoot ("app\build\outputs\apk\release\{0}" -f $outputFile)
if (-not (Test-Path $releaseApkPath)) {
    throw "Release APK was not found: $releaseApkPath"
}
if ($releaseApkPath -like '*-unsigned.apk') {
    throw "Release APK is unsigned: $releaseApkPath"
}

$badging = & $aaptPath dump badging $releaseApkPath
if ($LASTEXITCODE -ne 0) {
    throw "aapt badging failed with exit code $LASTEXITCODE."
}
$badgingText = ($badging | Out-String)
$packageName = Get-ApkBadgingValue $badgingText "package: name='([^']+)'"
$versionCode = Get-ApkBadgingValue $badgingText "versionCode='([^']+)'"
$versionName = Get-ApkBadgingValue $badgingText "versionName='([^']+)'"
$targetSdk = Get-ApkBadgingValue $badgingText "targetSdkVersion:'([^']+)'"
$applicationLabel = Get-ApkBadgingValue $badgingText "application-label:'([^']+)'"
$nativeCodeLine = ($badging | Where-Object { $_ -like 'native-code:*' } | Select-Object -First 1)
$nativeCodes = if ($nativeCodeLine) {
    [regex]::Matches($nativeCodeLine, "'([^']+)'") | ForEach-Object { $_.Groups[1].Value }
} else {
    @()
}
$detectedPlatform = Resolve-ArgusPlatform $nativeCodes
$resolvedPlatform = if ([string]::IsNullOrWhiteSpace($Platform)) {
    $detectedPlatform
} else {
    $Platform.Trim()
}

if (-not $packageName) {
    throw 'Package name could not be extracted from APK.'
}
if (-not $versionCode) {
    throw 'Version code could not be extracted from APK.'
}
if (-not $versionName) {
    throw 'Version name could not be extracted from APK.'
}
if (-not $targetSdk) {
    throw 'Target SDK could not be extracted from APK.'
}

& $apksignerPath verify --print-certs $releaseApkPath | Out-Null
if ($LASTEXITCODE -ne 0) {
    throw "apksigner verification failed with exit code $LASTEXITCODE."
}

$resolvedName = if ($Name) { $Name } elseif ($applicationLabel) { $applicationLabel } else { 'Ikar' }
$releaseVersion = if ($Version) { $Version } else { $versionName }
$stageDirectory = Join-Path $repoRoot ("build\argus-publication\v{0}" -f $versionCode)
if (-not (Test-Path $stageDirectory)) {
    New-Item -ItemType Directory -Path $stageDirectory | Out-Null
}

$stagedApkName = "{0}-{1}.apk" -f $Slug, $versionCode
$stagedApkPath = Join-Path $stageDirectory $stagedApkName
Copy-Item $releaseApkPath $stagedApkPath -Force

$metadata = [ordered]@{
    packagePath = $stagedApkPath
    slug = $Slug
    name = $resolvedName
    summary = $Summary
    description = $Description
    version = $releaseVersion
    channel = $Channel
    platform = $resolvedPlatform
    packageKind = 'apk'
    notes = if ($Notes) { $Notes } else { $null }
    repositoryUrl = if ($RepositoryUrl) { $RepositoryUrl } else { $null }
    homepageUrl = if ($HomepageUrl) { $HomepageUrl } else { $null }
    androidPackageName = $packageName
    androidVersionCode = [int]$versionCode
    targetSdkVersion = [int]$targetSdk
    isListed = (-not $Unlisted)
    verifiedFromApk = [ordered]@{
        outputFile = $releaseApkPath
        packageName = $packageName
        versionCode = [int]$versionCode
        versionName = $versionName
        targetSdkVersion = [int]$targetSdk
        nativeCodes = $nativeCodes
        detectedPlatform = $detectedPlatform
        applicationLabel = if ($applicationLabel) { $applicationLabel } else { $null }
        verifiedAt = [DateTimeOffset]::UtcNow.ToString('O')
    }
}

$metadataPath = Join-Path $stageDirectory 'argus-publication.json'
$metadata | ConvertTo-Json -Depth 6 | Set-Content -Path $metadataPath -Encoding UTF8

Write-Output "Prepared Argus publication files."
Write-Output "APK: $stagedApkPath"
Write-Output "Metadata: $metadataPath"
