# CNC 采集服务 - 一键安装脚本
# 脚本与CncCollector.exe放在同一目录，右键以管理员身份运行
# 用法:
#   .\install.ps1              # 默认 InstallUtil 方式（推荐）
#   .\install.ps1 -Method sc   # 使用 sc.exe 方式

param(
    [ValidateSet("installutil", "sc")]
    [string]$Method = "installutil"
)

$ErrorActionPreference = "Continue"
$serviceName = "CncCollector"
$installDir = $PSScriptRoot
$exePath = Join-Path $installDir "CncCollector.exe"

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "  CNC 机床数据采集服务 - 安装脚本 v3.0" -ForegroundColor Cyan
Write-Host "  安装方式: $Method" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "[错误] 请以管理员权限运行此脚本！" -ForegroundColor Red
    Write-Host "`n按回车键退出..." -ForegroundColor Gray
    Read-Host
    exit 1
}

# 检查 exe 是否存在
if (-not (Test-Path $exePath)) {
    Write-Host "[错误] 找不到 CncCollector.exe，请确认脚本和程序在同一目录。" -ForegroundColor Red
    Write-Host "  当前目录: $installDir" -ForegroundColor Yellow
    Write-Host "`n按回车键退出..." -ForegroundColor Gray
    Read-Host
    exit 1
}

# 检查 collector.json 是否存在
$configFile = Join-Path $installDir "collector.json"
if (-not (Test-Path $configFile)) {
    Write-Host "[警告] 找不到 collector.json，服务启动后可能无法正常工作。" -ForegroundColor Yellow
}

# 步骤1：检查并清理旧服务
Write-Host "`n[1/3] 检查旧服务..." -ForegroundColor Green
$existingService = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($existingService) {
    Write-Host "  服务已存在，正在停止并卸载..." -ForegroundColor Yellow
    if ($existingService.Status -eq 'Running') {
        Stop-Service -Name $serviceName -Force
        Start-Sleep -Seconds 3
    }
    # 卸载旧服务
    & $exePath --uninstall 2>$null
    if ($LASTEXITCODE -ne 0) {
        sc.exe delete $serviceName | Out-Null
    }
    Start-Sleep -Seconds 2
    Write-Host "  旧服务已卸载" -ForegroundColor Gray
} else {
    Write-Host "  无旧服务，跳过" -ForegroundColor Gray
}

# 步骤2：安装服务
Write-Host "[2/3] 安装Windows服务（方式: $Method）..." -ForegroundColor Green

switch ($Method) {
    "installutil" {
        # 使用内嵌的 ProjectInstaller + InstallUtil
        Write-Host "  使用 InstallUtil 安装..." -ForegroundColor Gray

        # 查找 InstallUtil.exe
        $installUtilPath = $null
        $runtimeDir = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
        $candidatePath = Join-Path $runtimeDir "InstallUtil.exe"
        if (Test-Path $candidatePath) {
            $installUtilPath = $candidatePath
        }
        if (-not $installUtilPath) {
            $fwPath = Join-Path $env:windir "Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
            if (Test-Path $fwPath) { $installUtilPath = $fwPath }
        }
        if (-not $installUtilPath) {
            $fwPath = Join-Path $env:windir "Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe"
            if (Test-Path $fwPath) { $installUtilPath = $fwPath }
        }

        if ($installUtilPath) {
            $result = & $installUtilPath "/LogFile=" "/LogToConsole=true" $exePath 2>&1
            Write-Host "  $result" -ForegroundColor Gray
        } else {
            Write-Host "  [警告] 未找到 InstallUtil，使用程序内置 --install 安装..." -ForegroundColor Yellow
            & $exePath --install
        }
    }

    "sc" {
        Write-Host "  使用 sc.exe 安装..." -ForegroundColor Gray
        sc.exe create $serviceName binPath= "`"$exePath`"" start= auto DisplayName= "CNC 机床数据采集服务" | Out-Null
        sc.exe description $serviceName "CNC机床HTTP采集、数据解析、产量跟踪和日终汇总" | Out-Null
    }
}

# 步骤3：配置恢复策略并启动
Write-Host "[3/3] 配置恢复策略并启动服务..." -ForegroundColor Green

# 失败后自动重启：第一次1分钟，第二次1分钟，之后每5分钟
sc.exe failure $serviceName reset= 0 actions= restart/60000/restart/60000/restart/300000 | Out-Null

# 启动服务
Start-Service -Name $serviceName -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3

$svc = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($svc -and $svc.Status -eq 'Running') {
    Write-Host "`n[成功] 采集服务已安装并启动！" -ForegroundColor Green
    Write-Host "  服务名称: $serviceName" -ForegroundColor Gray
    Write-Host "  安装目录: $installDir" -ForegroundColor Gray
    Write-Host "  安装方式: $Method" -ForegroundColor Gray
    Write-Host "  管理API:  http://localhost:5800/api/collector/status" -ForegroundColor Gray

    # 尝试调用管理API验证
    try {
        $apiKey = "collector_api_key_2026"
        if (Test-Path $configFile) {
            $configJson = Get-Content $configFile -Raw | ConvertFrom-Json
            if ($configJson.apiKey) { $apiKey = $configJson.apiKey }
        }
        $response = Invoke-WebRequest -Uri "http://localhost:5800/api/collector/status" -Headers @{ "X-Api-Key" = $apiKey } -TimeoutSec 5 -ErrorAction Stop
        Write-Host "  API状态:  $($response.StatusCode) - 服务运行正常" -ForegroundColor Green
    } catch {
        Write-Host "  API状态:  未响应（可能正在初始化）" -ForegroundColor Yellow
    }
} else {
    Write-Host "`n[警告] 服务已安装但未能启动，请检查配置和日志。" -ForegroundColor Yellow
    Write-Host "  日志目录: $installDir\logs\" -ForegroundColor Gray
    Write-Host "  运行日志:  collector.log" -ForegroundColor Gray
    Write-Host "  错误日志:  collector_error.log" -ForegroundColor Gray
}

Write-Host "`n常用命令:" -ForegroundColor Cyan
Write-Host "  启动: Start-Service $serviceName" -ForegroundColor Gray
Write-Host "  停止: Stop-Service $serviceName" -ForegroundColor Gray
Write-Host "  状态: Get-Service $serviceName" -ForegroundColor Gray
Write-Host "  卸载: .\uninstall.ps1" -ForegroundColor Gray
Write-Host "  控制台调试: .\CncCollector.exe --console" -ForegroundColor Gray

Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
