$ErrorActionPreference = "Stop"

Write-Host "ZAZ - Sambungan Google AI" -ForegroundColor Cyan
Write-Host "Cipta atau salin kunci anda dari https://aistudio.google.com/apikey"
Write-Host "Kunci tidak akan dipaparkan dan tidak disimpan dalam folder projek."
Write-Host ""

$secureKey = Read-Host "Tampal GEMINI_API_KEY" -AsSecureString
$keyPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureKey)
try {
    $plainKey = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($keyPointer).Trim()
    if ([string]::IsNullOrWhiteSpace($plainKey)) {
        throw "Kunci kosong. Tiada perubahan dibuat."
    }
    [Environment]::SetEnvironmentVariable("GEMINI_API_KEY", $plainKey, "User")
    Write-Host ""
    Write-Host "Google AI telah dikonfigurasi untuk akaun Windows ini." -ForegroundColor Green
    Write-Host "Tutup dan buka semula ZAZ. Lencana akan menunjukkan GOOGLE AI READY."
}
finally {
    if ($keyPointer -ne [IntPtr]::Zero) {
        [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($keyPointer)
    }
    Remove-Variable plainKey -ErrorAction SilentlyContinue
}
