$ErrorActionPreference = "Stop"

Write-Host ""
Write-Host "=== DURAKOMETR V1.10 PRODUCTION PREP ==="

$root = (Get-Location).Path
$appDir = Join-Path $root "app"
$srcDir = Join-Path $appDir "src\main"
$gradlePath = Join-Path $appDir "build.gradle.kts"
$backupDir = Join-Path $root ".v110-production-backup"

if (-not (Test-Path $gradlePath)) {
    throw "Не найден app\build.gradle.kts. Запусти скрипт из корня Android-проекта."
}

if (-not (Test-Path $srcDir)) {
    throw "Не найден app\src\main. Запусти скрипт из корня Android-проекта."
}

New-Item -ItemType Directory -Force -Path $backupDir | Out-Null

# ------------------------------------------------------------
# 1. Find exactly one TEST_MODE declaration that is still true.
# ------------------------------------------------------------

$ktFiles = Get-ChildItem `
    -Path $srcDir `
    -Recurse `
    -File `
    -Filter "*.kt"

$pattern = '(?m)^(?<indent>\s*)(?<prefix>(?:(?:private|public|internal)\s+)?(?:const\s+)?val\s+TEST_MODE\s*=\s*)true(?<tail>\s*(?://.*)?)$'

$testModeHits = @()

foreach ($file in $ktFiles) {

    $content = Get-Content `
        -LiteralPath $file.FullName `
        -Raw `
        -Encoding UTF8

    $matches = [regex]::Matches(
        $content,
        $pattern
    )

    foreach ($match in $matches) {
        $testModeHits += [PSCustomObject]@{
            File = $file.FullName
            Match = $match.Value
        }
    }
}

if ($testModeHits.Count -ne 1) {

    Write-Host ""
    Write-Host "Найдено объявлений TEST_MODE=true: $($testModeHits.Count)"

    if ($testModeHits.Count -gt 0) {
        $testModeHits | ForEach-Object {
            Write-Host "  $($_.File)"
            Write-Host "    $($_.Match)"
        }
    } else {

        Write-Host ""
        Write-Host "Все места, где встречается TEST_MODE:"

        foreach ($file in $ktFiles) {

            $content = Get-Content `
                -LiteralPath $file.FullName `
                -Raw `
                -Encoding UTF8

            if ($content -match 'TEST_MODE') {
                Write-Host "  $($file.FullName)"
            }
        }
    }

    throw "Ожидалось ровно одно объявление TEST_MODE=true. Ничего не изменено."
}

$testModeFile = $testModeHits[0].File
$testModeBackup = Join-Path $backupDir (Split-Path $testModeFile -Leaf)

Copy-Item `
    -LiteralPath $testModeFile `
    -Destination $testModeBackup `
    -Force

$testModeContent = Get-Content `
    -LiteralPath $testModeFile `
    -Raw `
    -Encoding UTF8

$testModeUpdated = [regex]::Replace(
    $testModeContent,
    $pattern,
    '${indent}${prefix}false${tail}',
    1
)

Set-Content `
    -LiteralPath $testModeFile `
    -Value $testModeUpdated `
    -Encoding UTF8

Write-Host "TEST_MODE: true -> false"
Write-Host "Файл: $testModeFile"

# ------------------------------------------------------------
# 2. Bump Android release version.
# ------------------------------------------------------------

Copy-Item `
    -LiteralPath $gradlePath `
    -Destination (Join-Path $backupDir "build.gradle.kts") `
    -Force

$gradle = Get-Content `
    -LiteralPath $gradlePath `
    -Raw `
    -Encoding UTF8

$codeMatch = [regex]::Match(
    $gradle,
    'versionCode\s*=\s*(\d+)'
)

$nameMatch = [regex]::Match(
    $gradle,
    'versionName\s*=\s*"([^"]+)"'
)

if (-not $codeMatch.Success) {
    throw "Не найден versionCode в app\build.gradle.kts"
}

if (-not $nameMatch.Success) {
    throw "Не найден versionName в app\build.gradle.kts"
}

$currentCode = [int]$codeMatch.Groups[1].Value
$currentName = $nameMatch.Groups[1].Value

if ($currentCode -gt 25) {
    throw "Текущий versionCode=$currentCode уже выше 25. Автоматически понижать версию нельзя."
}

if ($currentCode -lt 24) {
    throw "Неожиданный versionCode=$currentCode. Ожидался 24 или 25."
}

$gradle = [regex]::Replace(
    $gradle,
    'versionCode\s*=\s*\d+',
    'versionCode = 25',
    1
)

$gradle = [regex]::Replace(
    $gradle,
    'versionName\s*=\s*"[^"]+"',
    'versionName = "0.9.15"',
    1
)

Set-Content `
    -LiteralPath $gradlePath `
    -Value $gradle `
    -Encoding UTF8

Write-Host "Version: $currentCode / $currentName -> 25 / 0.9.15"

# ------------------------------------------------------------
# 3. Remove google-services.json safely if it still exists.
# ------------------------------------------------------------

$googleServices = Join-Path $appDir "google-services.json"

if (Test-Path $googleServices) {

    Move-Item `
        -LiteralPath $googleServices `
        -Destination (Join-Path $backupDir "google-services.json") `
        -Force

    Write-Host "google-services.json: убран в резервную папку"
} else {
    Write-Host "google-services.json: уже отсутствует"
}

# ------------------------------------------------------------
# 4. Static ZERO FIREBASE verification.
# ------------------------------------------------------------

$forbiddenPatterns = @(
    'com\.google\.firebase',
    '\bFirebaseAuth\b',
    '\bFirebaseFirestore\b',
    '\bFirebaseAppDistribution\b',
    '\bFirebaseUser\b',
    '\bgetIdToken\s*\('
)

$badHits = @()

foreach ($file in $ktFiles) {

    $content = Get-Content `
        -LiteralPath $file.FullName `
        -Raw `
        -Encoding UTF8

    foreach ($forbidden in $forbiddenPatterns) {

        if ($content -match $forbidden) {
            $badHits += "$($file.FullName) -> $forbidden"
        }
    }
}

$gradleFiles = Get-ChildItem `
    -Path $root `
    -Recurse `
    -File `
    -Include "*.gradle","*.gradle.kts"

foreach ($file in $gradleFiles) {

    if ($file.FullName -match '\\build\\') {
        continue
    }

    $content = Get-Content `
        -LiteralPath $file.FullName `
        -Raw `
        -Encoding UTF8

    if ($content -match 'firebase-(auth|firestore|appdistribution)') {
        $badHits += "$($file.FullName) -> Firebase dependency"
    }

    if (
        $file.FullName -eq $gradlePath -and
        $content -match 'com\.google\.gms\.google-services'
    ) {
        $badHits += "$($file.FullName) -> google-services plugin"
    }
}

if ($badHits.Count -gt 0) {

    Write-Host ""
    Write-Host "ОСТАЛИСЬ FIREBASE-ХВОСТЫ:"

    $badHits |
        Sort-Object -Unique |
        ForEach-Object {
            Write-Host "  $_"
        }

    throw "Production prep остановлен: сначала убрать найденные Firebase-хвосты."
}

# ------------------------------------------------------------
# 5. Verify TEST_MODE is now false.
# ------------------------------------------------------------

$finalTestModeContent = Get-Content `
    -LiteralPath $testModeFile `
    -Raw `
    -Encoding UTF8

if ($finalTestModeContent -notmatch '(?m)(?:const\s+)?val\s+TEST_MODE\s*=\s*false') {
    throw "TEST_MODE не подтверждён как false."
}

Write-Host ""
Write-Host "=== PREP COMPLETE ==="
Write-Host "TEST_MODE=false"
Write-Host "versionCode=25"
Write-Host "versionName=0.9.15"
Write-Host "Firebase Android refs=0"
Write-Host "Backup: $backupDir"
Write-Host ""
Write-Host "Теперь: Sync Project with Gradle Files -> Rebuild Project -> Generate Signed APK (release)."
