# Build all components: .NET backend + 2 React frontends
# Usage:
#   .\scripts\build-all.ps1            # Build all
#   .\scripts\build-all.ps1 -Clean     # Clean + Build
#   .\scripts\build-all.ps1 -Backend   # Backend only
#   .\scripts\build-all.ps1 -Frontend  # Frontends only
#   .\scripts\build-all.ps1 -Restore   # Just restore deps
[CmdletBinding()]
param(
    [switch]$Clean,
    [switch]$Backend,
    [switch]$Frontend,
    [switch]$Restore,
    [switch]$NoNpmInstall,
    [string]$Configuration = 'Release'
)

$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

$All = -not ($Backend -or $Frontend -or $Restore)

function Write-Step {
    param([string]$Message)
    Write-Host ""
    Write-Host "==========================================" -ForegroundColor Cyan
    Write-Host " $Message" -ForegroundColor Cyan
    Write-Host "==========================================" -ForegroundColor Cyan
}

function Test-CommandExists {
    param([string]$Command)
    return ($null -ne (Get-Command $Command -ErrorAction SilentlyContinue))
}

function Invoke-Step {
    param([string]$Description, [scriptblock]$Block)
    Write-Host "-> $Description" -ForegroundColor Yellow
    & $Block
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[FAIL] $Description" -ForegroundColor Red
        exit $LASTEXITCODE
    }
}

# Pre-flight checks
Write-Step "Pre-flight checks"
if (-not (Test-CommandExists 'dotnet')) {
    Write-Host "[ERROR] dotnet not found" -ForegroundColor Red
    exit 1
}

$dotnetVersion = (dotnet --version)
Write-Host "[OK] .NET SDK: $dotnetVersion" -ForegroundColor Green

if (Test-CommandExists 'node') {
    Write-Host "[OK] Node.js: $(node --version)" -ForegroundColor Green
}
if (Test-CommandExists 'npm') {
    Write-Host "[OK] npm:     $(npm --version)" -ForegroundColor Green
}

# Backend
if ($All -or $Backend -or $Restore -or $Clean) {
    if ($Clean) {
        Write-Step "Clean .NET solution"
        Invoke-Step "dotnet clean" { dotnet clean DH_Y_DUOC.slnx -c $Configuration -v minimal }
    }

    Write-Step ".NET: Restore packages"
    Invoke-Step "dotnet restore" { dotnet restore DH_Y_DUOC.slnx }

    if (-not $Restore) {
        Write-Step ".NET: Build solution ($Configuration)"
        Invoke-Step "dotnet build" { dotnet build DH_Y_DUOC.slnx -c $Configuration --no-restore -v minimal }
    }
}

# Frontends
if ($All -or $Frontend) {
    if (-not (Test-CommandExists 'npm')) {
        Write-Host "[WARN] Skip frontends (npm not installed)" -ForegroundColor Yellow
    }
    else {
        $frontends = @('fe0', 'fe-admin')
        foreach ($fe in $frontends) {
            $feDir = Join-Path $root $fe
            if (-not (Test-Path $feDir)) {
                Write-Host "[SKIP] $fe directory not found" -ForegroundColor Yellow
                continue
            }
            Write-Step "Frontend $fe : Build"
            Push-Location $feDir
            try {
                $needInstall = (-not $NoNpmInstall) -and ((-not (Test-Path 'node_modules')) -or $Clean)
                if ($needInstall) {
                    if ($Clean -and (Test-Path 'node_modules')) {
                        Write-Host "-> Clean: remove node_modules" -ForegroundColor Yellow
                        Remove-Item -Recurse -Force node_modules
                    }
                    Invoke-Step "npm install" { npm install }
                }
                else {
                    Write-Host "[OK] node_modules exists (skip npm install)" -ForegroundColor Green
                }

                if (-not $Restore) {
                    Invoke-Step "npm run build" { npm run build }
                }
            }
            finally {
                Pop-Location
            }
        }
    }
}

# Summary
Write-Step "BUILD COMPLETED"
Write-Host "  - .NET output:     src/Backend/DYD.Api/bin/$Configuration/net10.0/"
Write-Host "  - fe0 output:      fe0/dist/"
Write-Host "  - fe-admin output: fe-admin/dist/"
Write-Host ""
Write-Host "To run dev:" -ForegroundColor Cyan
Write-Host "  Backend:   dotnet run --project src/Backend/DYD.Api  (or F5 in VS)"
Write-Host "  Frontends: .\scripts\start-frontends.cmd"
Write-Host "  AI:        docker compose up -d qdrant aiservice"
Write-Host ""
