param(
    [string] $ProjectRoot = "<customer project root>",
    [string] $OutputPath = "",
    [string] $VivadoContextSrc = "",
    [string] $VitisPath = "",
    [string] $PsProjectRoot = "",
    [string] $AmdDocMcpEndpoint = "https://vivado.amd.com/mcp/doc-search"
)

$ErrorActionPreference = "Stop"

$packageRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$templatePath = Join-Path $packageRoot "docs\AI_AGENT_START_HERE.template.md"
if (-not (Test-Path -LiteralPath $templatePath)) {
    throw "Missing template: $templatePath"
}

if (-not $OutputPath) {
    $OutputPath = Join-Path $packageRoot "AI_AGENT_START_HERE.local.md"
}

$localConfigPath = Join-Path $packageRoot "config\repokey.local.json"
$localConfig = $null
if (Test-Path -LiteralPath $localConfigPath) {
    try {
        $localConfig = Get-Content -LiteralPath $localConfigPath -Raw | ConvertFrom-Json
    } catch {
        $localConfig = $null
    }
}

$vivadoPath = if ($env:VIVADO_PATH) {
    $env:VIVADO_PATH
} elseif ($localConfig -and $localConfig.vivadoInstallPath) {
    [string] $localConfig.vivadoInstallPath
} else {
    "<vivado bin path or vivado.bat>"
}
if ($VitisPath) {
    $resolvedVitisPath = $VitisPath
} elseif ($env:VITIS_PATH) {
    $resolvedVitisPath = $env:VITIS_PATH
} else {
    $resolvedVitisPath = "<vitis bin path or xsct path>"
}

$aiStackRoot = Join-Path $packageRoot "tools\ai_vitis_vivado_stack"

function Test-UsableProjectRoot {
    param([string] $Root)
    if ([string]::IsNullOrWhiteSpace($Root)) { return $false }
    if ($Root -match '[<>"]') { return $false }
    try {
        return (Test-Path -LiteralPath $Root)
    } catch {
        return $false
    }
}

# Per-project MCP configs live under the project so multiple projects on one
# machine do not overwrite each other's config inside the installed package.
# When no real project root is given (e.g. package setup renders the template
# with the "<customer project root>" placeholder), fall back to package-local
# configs so setup never fails on an invalid path.
if (Test-UsableProjectRoot $ProjectRoot) {
    $projectConfigDir = Join-Path $ProjectRoot ".vivado_ai_mcp\configs"
    $vitisMcpConfig = Join-Path $projectConfigDir "customer.vitis_mcp_config.json"
    $plQorMcpConfig = Join-Path $projectConfigDir "customer.pl_qor_mcp_config.json"
    New-Item -ItemType Directory -Force -Path $projectConfigDir | Out-Null
} else {
    $vitisMcpConfig = Join-Path $aiStackRoot "vitis_mcp\configs\customer.vitis_mcp_config.json"
    $plQorMcpConfig = Join-Path $aiStackRoot "pl_qor_mcp\configs\customer.pl_qor_mcp_config.json"
    $vitisConfigDir = Split-Path -Parent $vitisMcpConfig
    $plQorConfigDir = Split-Path -Parent $plQorMcpConfig
    New-Item -ItemType Directory -Force -Path $vitisConfigDir, $plQorConfigDir | Out-Null
    Write-Host "[INFO] No project root provided; MCP configs written package-local."
    Write-Host "[INFO] Re-run RepoKey-Setup.cmd and choose 'Init Project' to generate per-project MCP configs."
}
if (-not $VivadoContextSrc) {
    $VivadoContextSrc = Join-Path $ProjectRoot ".vivado_ai_mcp\context"
}
if (-not $PsProjectRoot) {
    $PsProjectRoot = $ProjectRoot
}

$vitisConfig = [ordered]@{
    project_root = $ProjectRoot
    vitis_path = $resolvedVitisPath
    evidence_root = (Join-Path $ProjectRoot ".vivado_ai_mcp\vitis")
    # Bitstream is a PL-side deliverable (RepoKey Vivado MCP write_bitstream).
    # Leave empty until the project has one; customers set it per project,
    # e.g. <project>\<project>.runs\impl_1\top.bit.
    bit_path = ""
    optional = $true
}
$vitisConfigJson = $vitisConfig | ConvertTo-Json -Depth 8
[System.IO.File]::WriteAllText($vitisMcpConfig, $vitisConfigJson, (New-Object System.Text.UTF8Encoding($false)))

$plQorAdapter = Join-Path $aiStackRoot "pl_optimizer_compat\scripts\repokey_pl_qor.py"
$plQorConfig = [ordered]@{
    adapter = $plQorAdapter
    python = "python"
    project_root = $ProjectRoot
    evidence_root = (Join-Path $ProjectRoot ".vivado_ai_mcp\qor")
    default_timeout_s = 120
    allow_collect = $true
    allow_experiment_generation = $true
}
$plQorConfigJson = $plQorConfig | ConvertTo-Json -Depth 8
[System.IO.File]::WriteAllText($plQorMcpConfig, $plQorConfigJson, (New-Object System.Text.UTF8Encoding($false)))

$content = Get-Content -LiteralPath $templatePath -Raw
$replacements = [ordered]@{
    "{{PROJECT_ROOT}}" = $ProjectRoot
    "{{PS_PROJECT_ROOT}}" = $PsProjectRoot
    "{{REPOKEY_ROOT}}" = $packageRoot
    "{{AI_STACK_ROOT}}" = $aiStackRoot
    "{{VIVADO_PATH}}" = $vivadoPath
    "{{VITIS_PATH}}" = $resolvedVitisPath
    "{{VIVADO_CONTEXT_SRC}}" = $VivadoContextSrc
    "{{VITIS_MCP_CONFIG}}" = $vitisMcpConfig
    "{{PL_QOR_MCP_CONFIG}}" = $plQorMcpConfig
    "{{AMD_DOC_MCP_ENDPOINT}}" = $AmdDocMcpEndpoint
}

foreach ($key in $replacements.Keys) {
    $content = $content.Replace($key, $replacements[$key])
}

$outDir = Split-Path -Parent $OutputPath
if ($outDir -and -not (Test-Path -LiteralPath $outDir)) {
    New-Item -ItemType Directory -Force -Path $outDir | Out-Null
}
$content = $content.TrimStart([char]0xFEFF)
[System.IO.File]::WriteAllText($OutputPath, $content, (New-Object System.Text.UTF8Encoding($false)))
Write-Host "[OK] Wrote $OutputPath"
