#!/usr/bin/env pwsh
# check-types.ps1 - 类型检查脚本
# 用法: ./scripts/check-types.ps1

$ErrorActionPreference = "Stop"
$ProjectRoot = Split-Path -Parent $PSScriptRoot

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  TypeScript Type Check Script" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

$ServerExit = 0
$DashboardExit = 0
$ExtensionExit = 0
$NodeAgentExit = 0

# 检查 server
Write-Host "[1/4] Checking server types..." -ForegroundColor Yellow
Set-Location "$ProjectRoot/server"
try {
    npx tsc --noEmit --skipLibCheck 2>&1 | Out-Null
    Write-Host "  ✅ Server types OK" -ForegroundColor Green
} catch {
    Write-Host "  ❌ Server types FAILED" -ForegroundColor Red
    npx tsc --noEmit --skipLibCheck 2>&1
    $ServerExit = 1
}

# 检查 dashboard
Write-Host "[2/4] Checking dashboard types..." -ForegroundColor Yellow
Set-Location "$ProjectRoot/dashboard"
try {
    npx tsc --noEmit --skipLibCheck 2>&1 | Out-Null
    Write-Host "  ✅ Dashboard types OK" -ForegroundColor Green
} catch {
    Write-Host "  ❌ Dashboard types FAILED" -ForegroundColor Red
    npx tsc --noEmit --skipLibCheck 2>&1
    $DashboardExit = 1
}

# 检查 extension
Write-Host "[3/4] Checking extension types..." -ForegroundColor Yellow
Set-Location "$ProjectRoot/extension"
try {
    npx tsc --noEmit --skipLibCheck 2>&1 | Out-Null
    Write-Host "  ✅ Extension types OK" -ForegroundColor Green
} catch {
    Write-Host "  ❌ Extension types FAILED" -ForegroundColor Red
    npx tsc --noEmit --skipLibCheck 2>&1
    $ExtensionExit = 1
}

# 检查 node-agent
Write-Host "[4/4] Checking node-agent types..." -ForegroundColor Yellow
if (Test-Path "$ProjectRoot/node-agent/tsconfig.json") {
    Set-Location "$ProjectRoot/node-agent"
    try {
        npx tsc --noEmit --skipLibCheck 2>&1 | Out-Null
        Write-Host "  ✅ Node-agent types OK" -ForegroundColor Green
    } catch {
        Write-Host "  ❌ Node-agent types FAILED" -ForegroundColor Red
        npx tsc --noEmit --skipLibCheck 2>&1
        $NodeAgentExit = 1
    }
} else {
    Write-Host "  ⏭️  Node-agent skipped (no tsconfig.json)" -ForegroundColor Gray
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan

$TotalErrors = $ServerExit + $DashboardExit + $ExtensionExit + $NodeAgentExit

if ($TotalErrors -eq 0) {
    Write-Host "  ✅ All type checks passed!" -ForegroundColor Green
    Write-Host "========================================" -ForegroundColor Cyan
    Set-Location $ProjectRoot
    exit 0
} else {
    Write-Host "  ❌ Type check failed with $TotalErrors error(s)" -ForegroundColor Red
    Write-Host "========================================" -ForegroundColor Cyan
    Set-Location $ProjectRoot
    exit 1
}
