# Import OpenAI API Key Powershell
# Simple script to pull the defined key from CS metadata and set in a prescribed location
# Need to run 'Set-ExecutionPolicy Unrestricted' in an Admin Powershell prompt before scripts are allowed to run
# Run with 'powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File <path to ps file>' if using scheduled task
# Make sure it is set to only run when user is logs on

param(
    [switch]$Silent
)

$logfile = Join-Path $PSScriptRoot "OpenAI_Import.log"

function Log {
    param([string]$msg)
    Write-Host $msg
    Add-Content -Path $logfile -Value $msg
}

Log "Starting OpenAI Import (Metadata Mode) -- $(Get-Date)"

# --------------------------------------------------
# STEP 1: Get metadata directly from CS
# --------------------------------------------------

try {
    $metadata = Invoke-RestMethod -Uri "https://metadata.cloudshare.com/api/v3/unauthenticated/metadata"

    $OPENAI = $metadata."custom-properties".openAIKey
    $CLASSID = $metadata."class-id"
# $CLASSID not used, but useful to see if updated on this VM. Could use to bypass if second boot

    Log "Class ID: $CLASSID"
    Log "OpenAI Key: $OPENAI"

} catch {
    Log "Failed to retrieve metadata"
    exit 1
}

if (-not $OPENAI -or $OPENAI -eq "null") {
    Log "No OpenAI key found in metadata"
    exit 1
}

# --------------------------------------------------
# STEP 2: Optional GUI prompt
# --------------------------------------------------

if (-not $Silent) {
    Add-Type -AssemblyName System.Windows.Forms
    $result = [System.Windows.Forms.MessageBox]::Show(
        "Install OpenAI key from metadata?",
        "OpenAI Key",
        "YesNo"
    )

    if ($result -ne "Yes") {
        Log "User cancelled"
        exit
    }
}

# --------------------------------------------------
# STEP 3: Write key to standard locations
# --------------------------------------------------

$keyFiles = @(
    "C:\course\openai_key.txt",
    "C:\Users\Student\keys\key.txt"
)

foreach ($file in $keyFiles) {
    $dir = Split-Path $file

    if (!(Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir | Out-Null
    }

    "OPENAI_API_KEY=$OPENAI" | Set-Content -Path $file
    Log "Wrote key to: $file"
}

# --------------------------------------------------
# STEP 4: Update any config files (if present)
# --------------------------------------------------

$configFiles = @(
    "C:\Users\Student\.config\shell_gpt\.sgptrc"
)
# Possible future use, but not for 1264

foreach ($file in $configFiles) {
    if (Test-Path $file) {
        (Get-Content $file) -replace "OPENAI_API_KEY=.*", "OPENAI_API_KEY=$OPENAI" |
            Set-Content $file

        Log "Updated config file: $file"
    }
}

# --------------------------------------------------
# STEP 5: Optional confirmation
# --------------------------------------------------

if (-not $Silent) {
    [System.Windows.Forms.MessageBox]::Show(
        "OpenAI key installed successfully",
        "OpenAI Key"
    )
}

Log "Completed successfully"
