# VideoD - yt-dlp ve ffmpeg'i tools/ klasorune indirir.
# Kullanim: powershell -ExecutionPolicy Bypass -File scripts\setup-tools.ps1

$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Betik hem depoda (scripts\ altinda) hem dagitim paketinde (kokte) calisir.
# Konuma gore koku dogru sec, yoksa araclar paketin disina inerdi.
$root = if ((Split-Path -Leaf $PSScriptRoot) -eq "scripts") {
    Split-Path -Parent $PSScriptRoot
} else {
    $PSScriptRoot
}
$tools = Join-Path $root "tools"
New-Item -ItemType Directory -Force $tools | Out-Null

# --- yt-dlp ---------------------------------------------------------------
$ytdlp = Join-Path $tools "yt-dlp.exe"
Write-Host "[1/2] yt-dlp indiriliyor..."
Invoke-WebRequest -Uri "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe" -OutFile $ytdlp
Write-Host "      OK: $ytdlp"

# --- ffmpeg ---------------------------------------------------------------
if (Test-Path (Join-Path $tools "ffmpeg.exe")) {
    Write-Host "[2/2] ffmpeg zaten mevcut, atlaniyor."
} else {
    Write-Host "[2/2] ffmpeg indiriliyor (~80-150 MB, biraz surebilir)..."
    $zip = Join-Path $env:TEMP "ffmpeg-videod.zip"
    $urls = @(
        "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip",
        "https://github.com/BtbN/FFmpeg-Builds/releases/latest/download/ffmpeg-master-latest-win64-gpl.zip"
    )
    $downloaded = $false
    foreach ($url in $urls) {
        try {
            Invoke-WebRequest -Uri $url -OutFile $zip
            $downloaded = $true
            break
        } catch {
            Write-Warning "Indirilemedi: $url"
        }
    }
    if (-not $downloaded) { throw "ffmpeg hicbir kaynaktan indirilemedi." }

    $extract = Join-Path $env:TEMP "ffmpeg-videod-extract"
    if (Test-Path $extract) { Remove-Item -Recurse -Force $extract }
    Expand-Archive $zip -DestinationPath $extract

    foreach ($exe in "ffmpeg.exe", "ffprobe.exe") {
        $found = Get-ChildItem $extract -Recurse -Filter $exe | Select-Object -First 1
        if ($found) { Copy-Item $found.FullName $tools -Force }
    }
    Remove-Item $zip -Force
    Remove-Item $extract -Recurse -Force
    Write-Host "      OK: $(Join-Path $tools 'ffmpeg.exe')"
}

Write-Host ""
Write-Host "Araclar hazir: $tools"
& $ytdlp --version
