param(
    [string] $ProjectRoot = ""
)

$ErrorActionPreference = "Stop"

if (-not $ProjectRoot) {
    Write-Host ""
    Write-Host "Init Project: enter the Vivado project folder that contains your .xpr."
    Write-Host "This step is required so RepoKey knows where to put the AI entry file."
    Write-Host ""
    while (-not $ProjectRoot) {
        $input = (Read-Host "Project root (type q to quit setup)").Trim().Trim('"')
        if ($input -eq "") {
            Write-Host "[ERROR] Project root is required. Enter a folder path, or type q to quit."
            continue
        }
        if ($input -match '^(q|quit)$') {
            Write-Host "[INFO] Setup stopped by user. Re-run RepoKey-Setup.cmd to continue later."
            exit 3
        }
        if (-not (Test-Path -LiteralPath $input)) {
            Write-Host "[ERROR] Path does not exist: $input"
            continue
        }
        $ProjectRoot = $input
    }
} else {
    if (-not (Test-Path -LiteralPath $ProjectRoot)) {
        Write-Host "[ERROR] Path does not exist: $ProjectRoot"
        Write-Host "[INFO] Nothing was changed. Re-run and enter a valid Vivado project folder."
        exit 2
    }
}

& (Join-Path $PSScriptRoot "init_project.ps1") $ProjectRoot -Force
exit $LASTEXITCODE
