# CNC 采集服务 - 快速测试脚本
# 无需安装Windows Service，直接在控制台模式下测试
# 用法: .\test.ps1

$ErrorActionPreference = "Continue"
$projectDir = Split-Path -Parent $PSScriptRoot
$exePath = Join-Path $projectDir "bin\CncCollector.exe"

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "  CNC 采集服务 - 快速测试脚本" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查exe
if (-not (Test-Path $exePath)) {
    Write-Host "[错误] 找不到 CncCollector.exe，请先编译。" -ForegroundColor Red
    Write-Host "  运行: dotnet build src\CncCollector\CncCollector.csproj -c Release" -ForegroundColor Yellow
    exit 1
}

# 检查数据库连接
Write-Host "`n[1/4] 检查数据库连接..." -ForegroundColor Green
$connStr = "Server=localhost;Database=cnc_business;Uid=root;Pwd=root;Charset=utf8mb4;SslMode=None;"
try {
    $conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
    $conn.Open()
    $cmd = $conn.CreateCommand()
    $cmd.CommandText = "SELECT COUNT(*) FROM cnc_collect_address WHERE is_enabled=1"
    $addrCount = $cmd.ExecuteScalar()
    Write-Host "  数据库连接成功，启用地址数: $addrCount" -ForegroundColor Gray
    $conn.Close()
} catch {
    Write-Host "  [警告] 数据库连接失败: $($_.Exception.Message)" -ForegroundColor Yellow
    Write-Host "  将使用模拟器模式测试..." -ForegroundColor Yellow
}

# 检查模拟器
Write-Host "`n[2/4] 检查CncSimulator模拟器..." -ForegroundColor Green
$simProcess = Get-Process -Name "CncSimulator" -ErrorAction SilentlyContinue
if ($simProcess) {
    Write-Host "  模拟器已在运行 (PID: $($simProcess.Id))" -ForegroundColor Gray
} else {
    $simPath = Join-Path (Split-Path -Parent (Split-Path -Parent $projectDir)) "src\CncSimulator\bin\CncSimulator.exe"
    $simPath2 = Join-Path $projectDir "..\..\CncSimulator\bin\CncSimulator.exe"
    if (Test-Path $simPath2) { $simPath = $simPath2 }
    
    if (Test-Path $simPath) {
        Write-Host "  启动模拟器: $simPath" -ForegroundColor Gray
        Start-Process $simPath
        Start-Sleep -Seconds 3
    } else {
        Write-Host "  [提示] 模拟器未找到，跳过。采集服务将连接配置的地址。" -ForegroundColor Yellow
    }
}

# 启动采集服务
Write-Host "`n[3/4] 启动采集服务（控制台模式）..." -ForegroundColor Green
Write-Host "  程序路径: $exePath" -ForegroundColor Gray
Write-Host "  配置文件: $(Join-Path $projectDir 'collector.json')" -ForegroundColor Gray
Write-Host "`n  >>> 采集服务输出 (按 Ctrl+C 退出) <<<`n" -ForegroundColor Yellow

$proc = Start-Process -FilePath $exePath -WorkingDirectory (Split-Path -Parent $exePath) -PassThru -NoNewWindow

# 等待启动
Start-Sleep -Seconds 5

# 测试管理API
Write-Host "`n[4/4] 测试管理API..." -ForegroundColor Green
try {
    $response = Invoke-RestMethod -Uri "http://localhost:5800/api/collector/status" -Headers @{ "X-API-Key" = "collector_api_key_2026" } -TimeoutSec 10
    Write-Host "  状态API响应:" -ForegroundColor Gray
    Write-Host "  运行中: $($response.data.isRunning)" -ForegroundColor Gray
    Write-Host "  工作线程: $($response.data.workerCount)" -ForegroundColor Gray
    Write-Host "  运行时间: $([math]::Round($response.data.uptimeSeconds, 1))秒" -ForegroundColor Gray
    Write-Host "`n[成功] 采集服务运行正常！" -ForegroundColor Green
} catch {
    Write-Host "  [警告] 状态API请求失败: $($_.Exception.Message)" -ForegroundColor Yellow
}

# 等待用户操作
Write-Host "`n采集服务正在运行中，按任意键停止..." -ForegroundColor Cyan
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

# 停止
if (-not $proc.HasExited) {
    Stop-Process -Id $proc.Id -Force
    Write-Host "采集服务已停止。" -ForegroundColor Gray
}
