$ErrorActionPreference = "Stop"

Write-Host "RepoKey Vivado AI self test"

$root = Resolve-Path (Join-Path $PSScriptRoot "..")
$exe = Join-Path $root "bin\repokey\repokey.exe"
$publicKey = Join-Path $root "config\public_key.pem"
$licenseFile = Join-Path $root "licenses\repokey-license.txt"

$failed = $false

function Test-RequiredPath {
    param(
        [string] $Label,
        [string] $Path
    )

    if (Test-Path -LiteralPath $Path) {
        Write-Host "[OK] $Label"
    } else {
        Write-Host "[MISSING] $Label"
        $script:failed = $true
    }
}

Test-RequiredPath "client exe: bin/repokey/repokey.exe" $exe
Test-RequiredPath "public key: config/public_key.pem" $publicKey

if (Test-Path -LiteralPath $licenseFile) {
    $licenseText = (Get-Content -LiteralPath $licenseFile -Raw -ErrorAction SilentlyContinue).Trim()
    if ($licenseText -and $licenseText.StartsWith("RK1.")) {
        Write-Host "[OK] license file: licenses/repokey-license.txt"
    } else {
        Write-Host "[WARN] license file exists but does not contain a valid RK1... license"
    }
} else {
    Write-Host "[WARN] license file is not installed yet: licenses/repokey-license.txt"
}

if ($env:VIVADO_PATH) {
    if (Test-Path -LiteralPath $env:VIVADO_PATH) {
        Write-Host "[OK] VIVADO_PATH"
    } else {
        Write-Host "[WARN] VIVADO_PATH is set but the path does not exist"
    }
} else {
    Write-Host "[WARN] VIVADO_PATH is not set"
}

if (-not $failed) {
    & $exe --help | Out-Null
    Write-Host "[OK] client command starts"
}

if ($failed) {
    exit 1
}

Write-Host "Self test finished"
