param(
    [Parameter(Mandatory=$true, Position=0)]
    [string] $ProjectRoot,
    [string] $VivadoContextSrc = "",
    [string] $VitisPath = "",
    [string] $AmdDocMcpEndpoint = "https://vivado.amd.com/mcp/doc-search",
    [switch] $Force
)

$ErrorActionPreference = "Stop"

if (-not (Test-Path -LiteralPath $ProjectRoot)) {
    throw "Project root does not exist: $ProjectRoot"
}

$resolvedProjectRoot = (Resolve-Path -LiteralPath $ProjectRoot).Path
$output = Join-Path $resolvedProjectRoot "AI_AGENT_START_HERE.local.md"

# If an old or same-named entry already exists in the project, back it up and
# replace it with a freshly rendered one (never silently overwrite, never block).
if (Test-Path -LiteralPath $output) {
    $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
    $backup = "$output.bak_$stamp"
    Copy-Item -LiteralPath $output -Destination $backup -Force
    Write-Host "[OK] Existing AI entry found: $output"
    Write-Host "[OK] Backed up to: $backup"
    Write-Host "[OK] Replacing it with a freshly generated entry."
} else {
    Write-Host "[OK] No existing AI entry; generating a new one."
}

& (Join-Path $PSScriptRoot "render_ai_start.ps1") -ProjectRoot $resolvedProjectRoot -OutputPath $output -VivadoContextSrc $VivadoContextSrc -VitisPath $VitisPath -AmdDocMcpEndpoint $AmdDocMcpEndpoint
Write-Host "[OK] Give this project-local file to the AI Agent first: $output"
