$ErrorActionPreference = "Stop"

Write-Host "RepoKey Vivado AI setup wizard"
Write-Host ""

$root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$licenseFile = Join-Path $root "licenses\repokey-license.txt"
$configDir = Join-Path $root "config"
$localConfig = Join-Path $configDir "repokey.local.json"
$client = Join-Path $root "repokey-client.cmd"
$aiStartFile = Join-Path $root "AI_AGENT_START_HERE.local.md"
$existingConfig = $null
if (Test-Path -LiteralPath $localConfig) {
    try {
        $existingConfig = Get-Content -Raw -LiteralPath $localConfig | ConvertFrom-Json
    } catch {
        $existingConfig = $null
    }
}

function Show-StopMessage {
    param([string] $Message)
    Write-Host ""
    Write-Host "[ACTION REQUIRED] $Message"
    Write-Host ""
    Write-Host "Close this window after reading the message, fix the issue, then double-click RepoKey-Setup.cmd again."
    exit 1
}

function Invoke-ClientCheck {
    param([string[]] $Arguments)
    $previousErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = "Continue"
    try {
        return & $client @Arguments 2>&1
    } finally {
        $ErrorActionPreference = $previousErrorActionPreference
    }
}

function Test-VivadoPath {
    param([string] $Path)
    if (-not $Path) { return $false }
    if (Test-Path -LiteralPath $Path) { return $true }
    if (Test-Path -LiteralPath (Join-Path $Path "vivado.bat")) { return $true }
    return $false
}

function Find-VivadoInstallations {
    $results = @()
    if ($env:XILINX_VIVADO) {
        $candidate = $env:XILINX_VIVADO
        if (Test-VivadoPath $candidate) { $results += $candidate }
    }
    foreach ($drive in @("D:", "C:", "E:")) {
        $root = Join-Path $drive "Xilinx"
        if (Test-Path -LiteralPath $root) {
            # vivado.bat lives at <Xilinx>\<version>\Vivado\<version>\bin\vivado.bat
            Get-ChildItem -LiteralPath $root -Recurse -Depth 5 -Filter "vivado.bat" -ErrorAction SilentlyContinue |
                Where-Object { $_.FullName -match "\\bin\\vivado\.bat$" } |
                Sort-Object FullName -Descending |
                ForEach-Object { $results += (Split-Path -Parent $_.FullName) }
        }
    }
    $fromPath = Get-Command vivado.bat -ErrorAction SilentlyContinue
    if ($fromPath) {
        $bin = Split-Path -Parent $fromPath.Source
        if (Test-VivadoPath $bin) { $results += $bin }
    }
    $seen = @{}
    $unique = @()
    foreach ($item in $results) {
        $key = $item.ToLowerInvariant()
        if (-not $seen.ContainsKey($key)) {
            $seen[$key] = $true
            $unique += $item
        }
    }
    return $unique
}

if (-not (Test-Path -LiteralPath $licenseFile)) {
    New-Item -ItemType Directory -Force -Path (Split-Path -Parent $licenseFile) | Out-Null
    New-Item -ItemType File -Force -Path $licenseFile | Out-Null
}

$rawLicenseText = Get-Content -LiteralPath $licenseFile -Raw -ErrorAction SilentlyContinue
$licenseText = if ($null -eq $rawLicenseText) { "" } else { $rawLicenseText.Trim() }
if ($licenseText -and $licenseText.StartsWith("RK1.")) {
    Write-Host "[OK] License file found: licenses\repokey-license.txt"
} else {
    Write-Host "[INFO] No License detected. Continuing in Free mode."
    Write-Host "      Free mode (Vivado access + project map) does not require a License."
    Write-Host "      Pro features require a License. Request one from the product website."
    Write-Host "      After receiving it, paste it into licenses\repokey-license.txt and run setup again."
}

$vivadoPath = $env:VIVADO_PATH
if ($vivadoPath -and (Test-Path -LiteralPath $vivadoPath)) {
    Write-Host "[OK] Existing VIVADO_PATH: $vivadoPath"
} elseif ($existingConfig -and $existingConfig.vivadoInstallPath -and (Test-Path -LiteralPath $existingConfig.vivadoInstallPath)) {
    $vivadoPath = [string] $existingConfig.vivadoInstallPath
    Write-Host "[OK] Existing installation detected; reusing saved Vivado path: $vivadoPath"
    Write-Host "[OK] Re-running setup repairs config and MCP registration."
} else {
    $detected = @(Find-VivadoInstallations)
    if ($detected.Count -gt 0) {
        Write-Host ""
        Write-Host "Detected Vivado installations on this machine:"
        for ($i = 0; $i -lt $detected.Count; $i++) {
            Write-Host ("  {0}) {1}" -f ($i + 1), $detected[$i])
        }
        Write-Host ("  {0}) Enter another path manually" -f ($detected.Count + 1))
        Write-Host ""
        while (-not $vivadoPath) {
            $choice = (Read-Host ("Choose 1-{0}" -f ($detected.Count + 1))).Trim()
            if ($choice -match '^\d+$') {
                $idx = [int]$choice - 1
                if ($idx -ge 0 -and $idx -lt $detected.Count) {
                    $vivadoPath = $detected[$idx]
                } elseif ($idx -eq $detected.Count) {
                    $manual = (Read-Host "Enter Vivado bin path or vivado.bat").Trim().Trim('"')
                    if (Test-VivadoPath $manual) { $vivadoPath = $manual }
                    else { Write-Host "[ERROR] That path does not contain vivado.bat. Try again." }
                } else {
                    Write-Host "[ERROR] Invalid choice. Try again."
                }
            } elseif ($choice -ne "") {
                if (Test-VivadoPath $choice) { $vivadoPath = $choice }
                else { Write-Host "[ERROR] That path does not contain vivado.bat. Try again." }
            } else {
                Write-Host "[ERROR] Vivado path is required. Choose a number above or enter a path."
            }
        }
    } else {
        Write-Host ""
        Write-Host "[ACTION REQUIRED] Vivado was not detected on this machine."
        Write-Host "RepoKey is a bridge to Vivado: Vivado must be installed first (the tool does not include Vivado)."
        Write-Host "Please install Vivado (2020.2 recommended), then re-run this setup."
        Write-Host "Or enter the bin directory that contains vivado.bat below."
        Write-Host ""
        while (-not $vivadoPath) {
            $manual = (Read-Host "Vivado bin path or vivado.bat (empty to exit)").Trim().Trim('"')
            if (-not $manual) {
                Show-StopMessage "No Vivado path provided. Install Vivado first, then re-run setup."
            }
            if (Test-VivadoPath $manual) { $vivadoPath = $manual }
            else { Write-Host "[ERROR] That path does not contain vivado.bat. Try again." }
        }
    }

    $env:VIVADO_PATH = $vivadoPath
    Write-Host "[OK] Using Vivado: $vivadoPath"
}

$config = [ordered]@{
    product = "RepoKey Vivado AI"
    licenseFile = "licenses/repokey-license.txt"
    vivadoInstallPath = $vivadoPath
    workspaceRoot = $root
}

$configJson = $config | ConvertTo-Json -Depth 4
[System.IO.File]::WriteAllText($localConfig, $configJson, (New-Object System.Text.UTF8Encoding($false)))
Write-Host "[OK] Wrote config\repokey.local.json"

[Environment]::SetEnvironmentVariable("REPOKEY_HOME", $root, "User")
$env:REPOKEY_HOME = $root
Write-Host "[OK] Set user environment variable REPOKEY_HOME: $root"

& (Join-Path $PSScriptRoot "render_ai_start.ps1") -ProjectRoot "<customer project root>" -OutputPath $aiStartFile

Write-Host ""
Write-Host "Running checks..."
$licenseCheckOutput = Invoke-ClientCheck @("license-status")
if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Host "[License check output]"
    Write-Host ($licenseCheckOutput -join [Environment]::NewLine)
    Show-StopMessage "License check failed. Confirm that licenses\repokey-license.txt contains the complete RK1... license from your email."
}

$envCheckOutput = Invoke-ClientCheck @("check-env")
if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Host "[Environment check output]"
    Write-Host ($envCheckOutput -join [Environment]::NewLine)
    Show-StopMessage "Environment check failed. Confirm the Vivado path and try again."
}

Write-Host ""
Write-Host "[OK] Setup finished."
Write-Host "[OK] REPOKEY_HOME is set for future terminals and AI sessions."
Write-Host ""
Write-Host "Registering RepoKey MCP automatically..."
$mcpSetup = Join-Path $PSScriptRoot "register_mcp.ps1"
try {
    & powershell -NoProfile -ExecutionPolicy Bypass -File $mcpSetup -Mode install
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[WARN] MCP registration did not complete. The base RepoKey installation is still valid."
    }
} catch {
    Write-Host "[WARN] MCP registration could not be completed automatically: $($_.Exception.Message)"
    Write-Host "[INFO] Re-run RepoKey-Setup.cmd and choose 'Register MCP' to retry it later."
}
Write-Host ""
Write-Host "Next step 1: fully close and restart your AI client once, such as VS Code/Codex, Claude Code, Cursor, Windsurf, or Cline."
Write-Host "Next step 2: re-run RepoKey-Setup.cmd, choose 'Init Project' and enter your Vivado project root, then give the generated AI_AGENT_START_HERE.local.md to the AI Agent."
Write-Host "Important: a new chat tab inside the same running AI client may not reload MCP configuration."
Write-Host "If RepoKey MCP cannot connect, the AI must stop and must not use direct Vivado scripts as a fallback."
Write-Host "If an AI Agent cannot read REPOKEY_HOME, tell it this RepoKey path: $root"



