$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

function Install-Collector([string]$DeviceName, [string]$DeviceToken) {
    $DataDir = Join-Path $env:LOCALAPPDATA 'CodexTokenMonitor'
    $BinDir = Join-Path $DataDir 'bin'
    $Config = Join-Path $DataDir 'config.json'
    $State = Join-Path $DataDir 'state.json'
    $Source = Join-Path $PSScriptRoot 'monitor-collector.exe'
    $Target = Join-Path $BinDir 'monitor-collector.exe'
    $TaskName = 'CodexTokenMonitor'

    $ExistingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
    if ($null -ne $ExistingTask) {
        Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
        Start-Sleep -Milliseconds 500
    }
    Get-Process -Name 'monitor-collector' -ErrorAction SilentlyContinue |
        Where-Object { $_.Path -eq $Target } |
        Stop-Process -Force -ErrorAction SilentlyContinue

    New-Item -ItemType Directory -Force -Path $BinDir | Out-Null
    Copy-Item -Force $Source $Target
    & $Target init -config $Config -server 'https://codex-token-monitor.tokencode.cloud' -token $DeviceToken -name $DeviceName
    if ($LASTEXITCODE -ne 0) {
        throw '保存采集器配置失败。'
    }
    & $Target -config $Config -state $State -once
    if ($LASTEXITCODE -ne 0) {
        throw '设备密钥无效或暂时无法连接服务器，请检查后重试。'
    }

    $Arguments = '-config "' + $Config + '" -state "' + $State + '"'
    $Action = New-ScheduledTaskAction -Execute $Target -Argument $Arguments
    $Trigger = New-ScheduledTaskTrigger -AtLogOn -User ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
    $Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 10 -RestartInterval (New-TimeSpan -Minutes 1)
    $Principal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
    Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger -Settings $Settings -Principal $Principal -Description 'Codex Token usage collector' -Force | Out-Null
    Start-ScheduledTask -TaskName $TaskName
}

$Form = New-Object System.Windows.Forms.Form
$Form.Text = 'Codex Token 监控安装器'
$Form.ClientSize = New-Object System.Drawing.Size(520, 300)
$Form.StartPosition = 'CenterScreen'
$Form.FormBorderStyle = 'FixedDialog'
$Form.MaximizeBox = $false

$Title = New-Object System.Windows.Forms.Label
$Title.Text = '安装 Token 监控采集器'
$Title.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 16, [System.Drawing.FontStyle]::Bold)
$Title.AutoSize = $true
$Title.Location = New-Object System.Drawing.Point(28, 22)
$Form.Controls.Add($Title)

$NameLabel = New-Object System.Windows.Forms.Label
$NameLabel.Text = '设备名称'
$NameLabel.AutoSize = $true
$NameLabel.Location = New-Object System.Drawing.Point(30, 78)
$Form.Controls.Add($NameLabel)

$NameBox = New-Object System.Windows.Forms.TextBox
$NameBox.Text = $env:COMPUTERNAME
$NameBox.Location = New-Object System.Drawing.Point(30, 100)
$NameBox.Size = New-Object System.Drawing.Size(458, 28)
$Form.Controls.Add($NameBox)

$TokenLabel = New-Object System.Windows.Forms.Label
$TokenLabel.Text = '设备密钥'
$TokenLabel.AutoSize = $true
$TokenLabel.Location = New-Object System.Drawing.Point(30, 140)
$Form.Controls.Add($TokenLabel)

$TokenBox = New-Object System.Windows.Forms.TextBox
$TokenBox.Location = New-Object System.Drawing.Point(30, 162)
$TokenBox.Size = New-Object System.Drawing.Size(458, 28)
$TokenBox.UseSystemPasswordChar = $true
$Form.Controls.Add($TokenBox)

$ShowToken = New-Object System.Windows.Forms.CheckBox
$ShowToken.Text = '显示密钥'
$ShowToken.AutoSize = $true
$ShowToken.Location = New-Object System.Drawing.Point(30, 198)
$ShowToken.Add_CheckedChanged({ $TokenBox.UseSystemPasswordChar = -not $ShowToken.Checked })
$Form.Controls.Add($ShowToken)

$StatusLabel = New-Object System.Windows.Forms.Label
$StatusLabel.Text = ''
$StatusLabel.AutoSize = $true
$StatusLabel.Location = New-Object System.Drawing.Point(30, 262)
$Form.Controls.Add($StatusLabel)

$InstallButton = New-Object System.Windows.Forms.Button
$InstallButton.Text = '安装并启动'
$InstallButton.Size = New-Object System.Drawing.Size(120, 38)
$InstallButton.Location = New-Object System.Drawing.Point(368, 218)
$InstallButton.Add_Click({
    $DeviceName = $NameBox.Text.Trim()
    $DeviceToken = $TokenBox.Text.Trim()
    if ([string]::IsNullOrWhiteSpace($DeviceName) -or [string]::IsNullOrWhiteSpace($DeviceToken)) {
        [System.Windows.Forms.MessageBox]::Show('请填写设备名称并粘贴设备密钥。', '信息不完整', 'OK', 'Warning') | Out-Null
        return
    }
    $InstallButton.Enabled = $false
    $StatusLabel.Text = '正在安装并验证设备密钥…'
    [System.Windows.Forms.Application]::DoEvents()
    try {
        Install-Collector -DeviceName $DeviceName -DeviceToken $DeviceToken
        $StatusLabel.Text = '安装完成，采集器已自动启动。'
        [System.Windows.Forms.MessageBox]::Show('安装完成。网站将在下一次刷新时显示这台电脑。', '安装成功', 'OK', 'Information') | Out-Null
        $Form.Close()
    } catch {
        $StatusLabel.Text = '安装失败，请检查提示后重试。'
        [System.Windows.Forms.MessageBox]::Show($_.Exception.Message, '安装失败', 'OK', 'Error') | Out-Null
    } finally {
        $InstallButton.Enabled = $true
    }
})
$Form.Controls.Add($InstallButton)

[void]$Form.ShowDialog()
