param(
    [string]$Confirmation
)

$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot
$Expected = "RESET insurance_s2"

Write-Host "即将重建数据库：insurance_s2_core、insurance_s2_agent、insurance_s2_analytics"
Write-Host "即将删除 Redis 前缀：ins:s2:*"
if ([string]::IsNullOrWhiteSpace($Confirmation)) {
    $Confirmation = Read-Host "请输入 $Expected 继续"
}
if ($Confirmation -cne $Expected) {
    throw "确认文本不匹配，已取消。"
}

Push-Location (Join-Path $ProjectRoot "backend")
try {
    uv run alembic -c alembic.ini --name alembic_analytics downgrade base
    if ($LASTEXITCODE -ne 0) { throw "Analytics 数据库清理失败。" }
    uv run alembic -c alembic.ini --name alembic_agent downgrade base
    if ($LASTEXITCODE -ne 0) { throw "Agent 数据库清理失败。" }
    uv run alembic -c alembic.ini --name alembic_core downgrade base
    if ($LASTEXITCODE -ne 0) { throw "Core 数据库清理失败。" }
    uv run python -m zbt.commands.reset_cache
    if ($LASTEXITCODE -ne 0) { throw "Redis 清理失败。" }
    & (Join-Path $PSScriptRoot "migrate.ps1")
    & (Join-Path $PSScriptRoot "seed.ps1")
    & (Join-Path $PSScriptRoot "build-analytics.ps1")
}
finally {
    Pop-Location
}
