param(
    [Parameter(Mandatory = $true)]
    [string]$DsnVariable,

    [switch]$ValidateOnly
)

$ErrorActionPreference = "Stop"

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Resolve-Path (Join-Path $scriptDir "..\..")
$fileVars = @{}

foreach ($envFile in @(".env", ".env.local")) {
    $envPath = Join-Path $repoRoot $envFile
    if (-not (Test-Path $envPath)) {
        continue
    }

    foreach ($line in Get-Content $envPath) {
        $trimmed = $line.Trim()
        if ($trimmed.Length -eq 0 -or $trimmed.StartsWith("#")) {
            continue
        }

        $index = $trimmed.IndexOf("=")
        if ($index -lt 1) {
            continue
        }

        $key = $trimmed.Substring(0, $index).Trim()
        $rawValue = $trimmed.Substring($index + 1).Trim()
        if (($rawValue.StartsWith('"') -and $rawValue.EndsWith('"')) -or ($rawValue.StartsWith("'") -and $rawValue.EndsWith("'"))) {
            $rawValue = $rawValue.Substring(1, $rawValue.Length - 2)
        }

        $fileVars[$key] = $rawValue
    }
}

$dsn = [Environment]::GetEnvironmentVariable($DsnVariable, "Process")
if ([string]::IsNullOrWhiteSpace($dsn) -and $fileVars.ContainsKey($DsnVariable)) {
    $dsn = $fileVars[$DsnVariable]
}

if ([string]::IsNullOrWhiteSpace($dsn)) {
    Write-Error "缺少环境变量：$DsnVariable"
    exit 2
}

$uvx = [Environment]::GetEnvironmentVariable("UVX_EXE", "Process")
if ([string]::IsNullOrWhiteSpace($uvx)) {
    $uvx = "C:\Dev\miniconda3\Scripts\uvx.exe"
}

if (-not (Test-Path $uvx)) {
    Write-Error "未找到 uvx：$uvx"
    exit 2
}

if ($ValidateOnly) {
    Write-Output "MCP PostgreSQL 启动配置检查通过：$DsnVariable"
    exit 0
}

$env:DATABASE_URI = $dsn
& $uvx --python "3.12" "postgres-mcp" "--access-mode=unrestricted"
exit $LASTEXITCODE
