$ErrorActionPreference = "Stop"

$repoRoot = Split-Path -Parent $PSScriptRoot
$projectFile = Join-Path $repoRoot "..\Project\TianyunV1.uvprojx"
$flagsFile = Join-Path $repoRoot "compile_flags.txt"
$outputFile = Join-Path $repoRoot "compile_commands.json"

if (!(Test-Path -LiteralPath $projectFile)) {
    throw "Keil project file not found: $projectFile"
}

if (!(Test-Path -LiteralPath $flagsFile)) {
    throw "compile_flags.txt not found: $flagsFile"
}

[xml]$project = Get-Content -LiteralPath $projectFile

$fileNodes = $project.SelectNodes("//File[FileType='1']/FilePath")
if ($null -eq $fileNodes -or $fileNodes.Count -eq 0) {
    throw "No C source files found in project."
}

$baseFlags = [System.IO.File]::ReadAllLines($flagsFile) |
    Where-Object { $_.Trim().Length -gt 0 } |
    ForEach-Object { [string]$_ }

$compileDb = @()

foreach ($node in $fileNodes) {
    $relativePath = $node.'#text'
    if (![string]::IsNullOrWhiteSpace($relativePath) -and $relativePath.ToLower().EndsWith(".c")) {
        $resolved = [System.IO.Path]::GetFullPath((Join-Path (Split-Path -Parent $projectFile) $relativePath))
        $arguments = @("clang") + @($baseFlags) + @("-c", [string]$resolved)
        $command = "clang " + ($baseFlags -join " ") + " -c `"$resolved`""

        $compileDb += [PSCustomObject]@{
            directory = $repoRoot
            file = $resolved
            command = $command
            arguments = $arguments
        }
    }
}

$compileDb |
    ConvertTo-Json -Depth 4 |
    Set-Content -LiteralPath $outputFile -Encoding utf8

Write-Output "Generated: $outputFile"
Write-Output "Entries: $($compileDb.Count)"
