$ErrorActionPreference = 'Stop'

$Root = $PSScriptRoot
$Binary = Join-Path $Root 'zfile\zfile-pro.exe'
$Result = 0

function Get-ZFileProcesses {
    $binaryPath = [IO.Path]::GetFullPath($Binary)
    @(Get-CimInstance Win32_Process -Filter "Name='zfile-pro.exe'" -ErrorAction SilentlyContinue |
        Where-Object {
            $_.ExecutablePath -and
            [string]::Equals(
                [IO.Path]::GetFullPath($_.ExecutablePath),
                $binaryPath,
                [StringComparison]::OrdinalIgnoreCase
            )
        })
}

if (-not (Test-Path $Binary -PathType Leaf)) {
    Write-Host '错误: 找不到 zfile\zfile-pro.exe' -ForegroundColor Red
    Write-Host '请确保解压完整，并在解压目录中运行此脚本'
    $Result = 1
} elseif (@(Get-ZFileProcesses).Count -gt 0) {
    Write-Host 'zfile-pro 已在运行，无需重复启动'
} else {
    Write-Host '正在后台启动 zfile-pro...'
    try {
        $process = Start-Process -FilePath $Binary `
            -ArgumentList '-Dfile.encoding=UTF-8', '-Dsun.stdout.encoding=UTF-8', '-Dsun.stderr.encoding=UTF-8' `
            -WorkingDirectory $Root `
            -WindowStyle Hidden `
            -PassThru
        Start-Sleep -Seconds 2
        $process.Refresh()
        if ($process.HasExited) {
            throw '程序启动后立即退出，请查看日志确认原因'
        }

        Write-Host ''
        Write-Host '已在后台启动，可关闭本窗口。'
        Write-Host ('日志目录: ' + (Join-Path $env:USERPROFILE '.zfile-v4\logs'))
        Write-Host '停止服务请运行: 停止服务.bat'
    } catch {
        Write-Host ("后台启动失败: " + $_.Exception.Message) -ForegroundColor Red
        $Result = 1
    }
}

Write-Host ''
Write-Host '按任意键退出...'
exit $Result
