# 安装依赖 - 直播延迟播放器
$ErrorActionPreference = "Continue"
$InstallDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ToolsDir = Join-Path $InstallDir "tools"
$FfmpegDir = Join-Path $ToolsDir "ffmpeg"

Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "           一键安装所有依赖" -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""

# ============================================================
#  Step 1: Python
# ============================================================
Write-Host "[1/3] 检查 Python..." -ForegroundColor Yellow
$pythonCmd = $null

$py = Get-Command python -ErrorAction SilentlyContinue
if ($py) {
    $ver = & python --version 2>&1
    Write-Host "[OK] Python 已安装: $ver" -ForegroundColor Green
    $pythonCmd = "python"
} else {
    $pyLauncher = Get-Command py -ErrorAction SilentlyContinue
    if ($pyLauncher) {
        $ver = & py --version 2>&1
        Write-Host "[OK] Python Launcher 已安装: $ver" -ForegroundColor Green
        $pythonCmd = "py"
    }
}

if (-not $pythonCmd) {
    Write-Host "[X] Python 未安装，使用 winget 安装..." -ForegroundColor Red
    winget install Python.Python.3.12 --accept-package-agreements --accept-source-agreements
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    $py = Get-Command python -ErrorAction SilentlyContinue
    if ($py) { $pythonCmd = "python" }
}

# ============================================================
#  Step 2: Flask
# ============================================================
if ($pythonCmd) {
    Write-Host ""
    Write-Host "[2/3] 安装 Flask..." -ForegroundColor Yellow
    & $pythonCmd -m pip install flask -q 2>&1 | Out-Null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "[OK] Flask 安装完成" -ForegroundColor Green
    } else {
        Write-Host "[X] Flask 安装失败" -ForegroundColor Red
    }
} else {
    Write-Host ""
    Write-Host "[2/3] 跳过 Flask（Python 未就绪）" -ForegroundColor DarkGray
}

# ============================================================
#  Step 3: FFmpeg
# ============================================================
Write-Host ""
Write-Host "[3/3] 检查 FFmpeg..." -ForegroundColor Yellow

$ffmpegSys = Get-Command ffmpeg -ErrorAction SilentlyContinue
if ($ffmpegSys) {
    Write-Host "[OK] FFmpeg 已在系统 PATH 中" -ForegroundColor Green
} elseif (Test-Path (Join-Path $FfmpegDir "ffmpeg.exe")) {
    Write-Host "[OK] FFmpeg 已在本地 tools\ffmpeg\" -ForegroundColor Green
} else {
    Write-Host "[X] FFmpeg 未安装，使用 winget 安装..." -ForegroundColor Yellow
    winget install Gyan.FFmpeg --accept-package-agreements --accept-source-agreements
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
    $ffmpegSys = Get-Command ffmpeg -ErrorAction SilentlyContinue
    if ($ffmpegSys) {
        Write-Host "[OK] FFmpeg 安装完成" -ForegroundColor Green
    } else {
        Write-Host "[!] winget 安装失败，尝试下载到本地..." -ForegroundColor Yellow
        if (-not (Test-Path $FfmpegDir)) { New-Item -ItemType Directory -Path $FfmpegDir -Force | Out-Null }
        $url = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
        $zip = Join-Path $env:TEMP "ffmpeg_dl.zip"
        $extract = Join-Path $env:TEMP "ffmpeg_dl_extract"
        try {
            $ProgressPreference = 'SilentlyContinue'
            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
            Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing
            if (Test-Path $extract) { Remove-Item $extract -Recurse -Force }
            Expand-Archive -Path $zip -DestinationPath $extract -Force
            $ff = Get-ChildItem -Path $extract -Filter "ffmpeg.exe" -Recurse | Select-Object -First 1
            if ($ff) {
                Copy-Item $ff.FullName (Join-Path $FfmpegDir "ffmpeg.exe") -Force
                $fp = Get-ChildItem -Path $extract -Filter "ffprobe.exe" -Recurse | Select-Object -First 1
                if ($fp) { Copy-Item $fp.FullName (Join-Path $FfmpegDir "ffprobe.exe") -Force }
                Write-Host "[OK] FFmpeg 下载完成" -ForegroundColor Green
            }
            Remove-Item $zip -Force -ErrorAction SilentlyContinue
            Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
        } catch {
            Write-Host "[!] 下载失败: $_" -ForegroundColor Red
        }
    }
}

# ============================================================
#  Node.js (仅检测)
# ============================================================
Write-Host ""
$node = Get-Command node -ErrorAction SilentlyContinue
if ($node) {
    $nv = & node --version 2>&1
    Write-Host "[OK] Node.js: $nv" -ForegroundColor Green
} else {
    Write-Host "[i] Node.js 未安装（可选，不影响基本功能）" -ForegroundColor DarkGray
}

Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "   完成！双击 启动服务.bat 运行" -ForegroundColor Green
Write-Host "   浏览器打开 http://localhost:8090" -ForegroundColor Green
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""
Read-Host "按回车退出"
