# setup_venv.ps1 — AI Trailer Generator v2 — Virtual Environment Setup
# Run once: .\setup_venv.ps1
# -----------------------------------------------------------------------
# If blocked by ExecutionPolicy:
#   Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

$ErrorActionPreference = "Stop"
$VENV_DIR = ".venv"

function Invoke-CapturedProcess {
    param(
        [Parameter(Mandatory = $true)][string]$FilePath,
        [Parameter(Mandatory = $false)][string[]]$Arguments = @()
    )

    $psi = [System.Diagnostics.ProcessStartInfo]::new()
    $psi.FileName = $FilePath
    foreach ($arg in $Arguments) {
        [void]$psi.ArgumentList.Add($arg)
    }
    $psi.UseShellExecute = $false
    $psi.RedirectStandardOutput = $true
    $psi.RedirectStandardError = $true
    $psi.CreateNoWindow = $true

    $process = [System.Diagnostics.Process]::Start($psi)
    $stdout = $process.StandardOutput.ReadToEnd()
    $stderr = $process.StandardError.ReadToEnd()
    $process.WaitForExit()

    $combined = (($stdout + "`n" + $stderr).Trim())
    if ($process.ExitCode -ne 0) {
        throw "Command failed ($($process.ExitCode)): $FilePath $($Arguments -join ' ')`n$combined"
    }
    return $combined
}

function Resolve-ProjectPython {
    $cmd = Get-Command python -ErrorAction SilentlyContinue
    if ($cmd) {
        return $cmd.Source
    }

    $candidates = @(
        "$env:LOCALAPPDATA\Programs\Python\Python311\python.exe",
        "$env:LOCALAPPDATA\Microsoft\WindowsApps\python.exe"
    )

    foreach ($candidate in $candidates) {
        if ($candidate -and (Test-Path $candidate)) {
            return $candidate
        }
    }

    throw "Python 3.11+ not found. Install Python 3.11+ or add it to PATH."
}

Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "  AI Trailer Generator v2 — venv Setup" -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""

# ---- 1. Check Python version ------------------------------------------------
$PROJECT_PYTHON = Resolve-ProjectPython
$pythonVersion = Invoke-CapturedProcess $PROJECT_PYTHON @("--version")
Write-Host "Python: $pythonVersion"
if ($pythonVersion -notmatch "3\.(1[1-9]|[2-9]\d)") {
    Write-Error "Python 3.11+ required. Found: $pythonVersion"
    exit 1
}

# ---- 2. Create venv ---------------------------------------------------------
if (Test-Path $VENV_DIR) {
    $existingVenvPython = Join-Path $VENV_DIR "Scripts\python.exe"
    $venvOk = $false
    if (Test-Path $existingVenvPython) {
        try {
            $existingVersion = Invoke-CapturedProcess $existingVenvPython @("--version")
            $venvOk = $existingVersion -match "3\.(1[1-9]|[2-9]\d)"
        } catch {
            $venvOk = $false
        }
    }

    if ($venvOk) {
        Write-Host "Virtual environment already exists at '$VENV_DIR'. Skipping creation." -ForegroundColor Yellow
    } else {
        Write-Host "Existing virtual environment is not usable. Recreating '$VENV_DIR' ..." -ForegroundColor Yellow
        Remove-Item -LiteralPath $VENV_DIR -Recurse -Force
        Invoke-CapturedProcess $PROJECT_PYTHON @("-m", "venv", $VENV_DIR) | Out-Null
        Write-Host "Done." -ForegroundColor Green
    }
} else {
    Write-Host "Creating virtual environment in '$VENV_DIR' ..." -ForegroundColor Green
    Invoke-CapturedProcess $PROJECT_PYTHON @("-m", "venv", $VENV_DIR) | Out-Null
    Write-Host "Done." -ForegroundColor Green
}

# ---- 3. Activate venv -------------------------------------------------------
$activate = Join-Path $VENV_DIR "Scripts\Activate.ps1"
Write-Host "Activating virtual environment ..."
. $activate
$VENV_PYTHON = Join-Path $VENV_DIR "Scripts\python.exe"

# ---- 4. Upgrade pip ---------------------------------------------------------
Write-Host "Upgrading pip ..." -ForegroundColor Green
& $VENV_PYTHON -m pip install --upgrade pip --quiet

# ---- 5. Install dependencies ------------------------------------------------
Write-Host "Installing dependencies from requirements.txt ..." -ForegroundColor Green
& $VENV_PYTHON -m pip install -r requirements.txt

# ---- 6. Copy .env if missing ------------------------------------------------
if (-not (Test-Path ".env")) {
    if (Test-Path ".env.example") {
        Copy-Item ".env.example" ".env"
        Write-Host ""
        Write-Host "  .env created from .env.example." -ForegroundColor Yellow
        Write-Host "  >>> Open .env and fill in your OPENROUTER_API_KEY! <<<" -ForegroundColor Red
    }
}

# ---- 7. Done ----------------------------------------------------------------
Write-Host ""
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "  Setup complete!" -ForegroundColor Green
Write-Host ""
Write-Host "  Activate the venv with:"
Write-Host "    .\.venv\Scripts\Activate.ps1" -ForegroundColor White
Write-Host ""
Write-Host "  Then run the pipeline:"
Write-Host "    python cli.py run --no-audio --no-llm" -ForegroundColor White
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""
