<#
.SYNOPSIS
    PowerToggle 安装脚本
.DESCRIPTION
    安装 PowerToggle 到 %LOCALAPPDATA%\PowerToggle,创建开机自启快捷方式,并启动程序。
    无需管理员权限。
.NOTES
    运行方式: 右键 -> 使用 PowerShell 运行
    或: powershell -ExecutionPolicy Bypass -File install.ps1
#>

$ErrorActionPreference = "Stop"
$InstallerDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$InstallDir = "$env:LOCALAPPDATA\PowerToggle"
$StartupDir = [Environment]::GetFolderPath("Startup")
$ShortcutPath = "$StartupDir\PowerToggle.lnk"

function Write-Step($msg) { Write-Host "[*] $msg" -ForegroundColor Cyan }
function Write-Ok($msg)   { Write-Host "[+] $msg" -ForegroundColor Green }
function Write-Warn($msg)  { Write-Host "[!] $msg" -ForegroundColor Yellow }
function Write-Err($msg)   { Write-Host "[-] $msg" -ForegroundColor Red }

Write-Host ""
Write-Host "  ================================" -ForegroundColor Magenta
Write-Host "     PowerToggle 安装程序 v1.0" -ForegroundColor Magenta
Write-Host "  ================================" -ForegroundColor Magenta
Write-Host ""

# ============================================================
# 步骤 1: 检查 .NET Framework 4.5+
# ============================================================
Write-Step "正在检查 .NET Framework..."

$netKey = "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
$netRelease = (Get-ItemProperty $netKey -Name Release -ErrorAction SilentlyContinue).Release

if ($netRelease -ge 378389) {
    $netVersion = switch ($netRelease) {
        { $_ -ge 533320 } { "4.8.1"; break }
        { $_ -ge 528040 } { "4.8"; break }
        { $_ -ge 461808 } { "4.7.2"; break }
        { $_ -ge 394802 } { "4.6.2"; break }
        { $_ -ge 379893 } { "4.5.2"; break }
        { $_ -ge 378389 } { "4.5"; break }
        default { "4.5+" }
    }
    Write-Ok "检测到 .NET Framework $netVersion"
} else {
    Write-Err "未找到 .NET Framework 4.5+,此程序需要该运行环境。"
    Write-Host ""
    Write-Host "    请从以下地址下载并安装 .NET Framework 4.8:" -ForegroundColor White
    Write-Host "    https://dotnet.microsoft.com/download/dotnet-framework" -ForegroundColor White
    Write-Host ""
    Read-Host "按回车键退出"
    exit 1
}

# ============================================================
# 步骤 2: 检查 Windows 版本
# ============================================================
Write-Step "正在检查 Windows 版本..."

$osInfo = Get-CimInstance Win32_OperatingSystem
$buildNumber = [int]($osInfo.BuildNumber)

if ($buildNumber -ge 16299) {
    Write-Ok "Windows Build $buildNumber(支持电源模式滑条同步)"
} elseif ($buildNumber -ge 10240) {
    Write-Warn "Windows Build $buildNumber(不支持电源模式滑条,仅基本功能可用)"
} else {
    Write-Warn "检测到较旧的 Windows 版本,可能无法正常工作。"
}

$manufacturer = (Get-CimInstance Win32_ComputerSystem).Manufacturer
if ($manufacturer -match "LENOVO|Lenovo") {
    Write-Ok "检测到联想电脑 - 将启用 ITS 冲突防护"
}

# ============================================================
# 步骤 3: 停止已运行的实例
# ============================================================
Write-Step "正在停止已运行的实例..."

$existing = Get-Process PowerToggle -ErrorAction SilentlyContinue
if ($existing) {
    $existing | Stop-Process -Force
    Start-Sleep -Milliseconds 500
    Write-Ok "已停止旧实例"
} else {
    Write-Ok "无运行中的实例"
}

# ============================================================
# 步骤 4: 安装文件
# ============================================================
Write-Step "正在安装到 $InstallDir ..."

if (!(Test-Path $InstallDir)) {
    New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
}

# 复制程序
# 两种运行形态都支持:
#   1) 发行包:exe 与本脚本放在同一目录(用户下载解压后直接运行)
#   2) 仓库内:exe 在 ../release/ 下(克隆仓库后直接跑脚本)
$exeSrc = Join-Path $InstallerDir "PowerToggle.exe"
if (-not (Test-Path $exeSrc)) {
    $repoExe = Join-Path (Split-Path $InstallerDir -Parent) "release\PowerToggle.exe"
    if (Test-Path $repoExe) { $exeSrc = $repoExe }
}
if (Test-Path $exeSrc) {
    Copy-Item $exeSrc "$InstallDir\PowerToggle.exe" -Force
    Write-Ok "已安装 PowerToggle.exe"
} else {
    Write-Err "未找到 PowerToggle.exe!"
    Write-Host "    预期路径: $exeSrc" -ForegroundColor White
    Read-Host "按回车键退出"
    exit 1
}

# ============================================================
# 步骤 5: 配置文件检查
# ============================================================
$configFile = "$InstallDir\PowerToggle.ini"
if (Test-Path $configFile) {
    Write-Step "发现已有配置文件 - 保留当前设置"
} else {
    Write-Ok "首次安装 - 首次运行时将自动创建电源方案"
}

# ============================================================
# 步骤 6: 创建开机自启快捷方式
# ============================================================
Write-Step "正在创建开机自启快捷方式..."

try {
    $shell = New-Object -ComObject WScript.Shell
    $shortcut = $shell.CreateShortcut($ShortcutPath)
    $shortcut.TargetPath = "$InstallDir\PowerToggle.exe"
    $shortcut.WorkingDirectory = $InstallDir
    $shortcut.Description = "PowerToggle - 电源模式切换工具"
    $shortcut.WindowStyle = 1
    $shortcut.Save()
    Write-Ok "已创建开机自启快捷方式"
} catch {
    Write-Warn "无法创建快捷方式: $_"
}

# ============================================================
# 步骤 7: 启动程序
# ============================================================
Write-Step "正在启动 PowerToggle..."

Start-Process "$InstallDir\PowerToggle.exe"
Start-Sleep -Seconds 2

$running = Get-Process PowerToggle -ErrorAction SilentlyContinue
if ($running) {
    Write-Ok "PowerToggle 已启动 (PID: $($running.Id))"
} else {
    Write-Warn "PowerToggle 可能启动失败。"
    Write-Host "    请尝试手动运行: $InstallDir\PowerToggle.exe" -ForegroundColor White
}

# ============================================================
# 完成
# ============================================================
Write-Host ""
Write-Ok "安装完成!"
Write-Host ""
Write-Host "  使用方法:" -ForegroundColor White
Write-Host "    左键点击托盘图标 = 切换电源模式" -ForegroundColor Gray
Write-Host "    右键点击托盘图标 = 打开菜单(设置、退出)" -ForegroundColor Gray
Write-Host ""
Write-Host "  安装位置: $InstallDir" -ForegroundColor Gray
Write-Host "  开机自启: $ShortcutPath" -ForegroundColor Gray
Write-Host ""
Write-Host "  卸载方法: 运行 uninstall.ps1" -ForegroundColor Gray
Write-Host ""
Read-Host "按回车键关闭"