# Build AI Maketing Facebook cho Windows (folder + zip; tùy chọn Inno Setup)
# Chạy trên Windows:  powershell -ExecutionPolicy Bypass -File packaging\build_windows.ps1

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
Set-Location $Root

Write-Host "=== [1/5] Cài PyInstaller + deps ===" -ForegroundColor Cyan
python -m pip install -q --upgrade pip
python -m pip install -q "pyinstaller>=6.0" -r requirements.txt

Write-Host "=== [2/5] Clean ===" -ForegroundColor Cyan
Remove-Item -Recurse -Force build\AI_Maketing_Facebook, dist\AI_Maketing_Facebook -ErrorAction SilentlyContinue
Remove-Item -Force dist\AI_Maketing_Facebook_Windows.zip -ErrorAction SilentlyContinue

Write-Host "=== [3/5] PyInstaller ===" -ForegroundColor Cyan
python -m PyInstaller --noconfirm --clean packaging\AI_Maketing_Facebook.spec

$Out = Join-Path $Root "dist\AI_Maketing_Facebook"
if (-not (Test-Path $Out)) {
    Write-Error "Build thất bại — không thấy dist\AI_Maketing_Facebook"
}

Write-Host "=== [4/5] Playwright Chromium ===" -ForegroundColor Cyan
$Browsers = Join-Path $Out "ms-playwright"
New-Item -ItemType Directory -Force -Path $Browsers | Out-Null
$env:PLAYWRIGHT_BROWSERS_PATH = $Browsers
python -m playwright install chromium
if (-not $?) { Write-Warning "playwright install chromium lỗi — user cài sau" }

# copy hướng dẫn + sample
Copy-Item packaging\HUONG_DAN_CAI_DAT.txt $Out -ErrorAction SilentlyContinue
Copy-Item README.txt, proxies.txt, vietnamese_names.txt, LIMITS_GUIDE.txt $Out -ErrorAction SilentlyContinue
Copy-Item packaging\CAI_DAT_WINDOWS.cmd $Out -ErrorAction SilentlyContinue

# first-run helper
@"
@echo off
chcp 65001 >nul
cd /d "%~dp0"
set PLAYWRIGHT_BROWSERS_PATH=%~dp0ms-playwright
if not exist "%PLAYWRIGHT_BROWSERS_PATH%\chromium-*" (
  echo Dang cai Chromium cho Playwright lan dau...
  python -m playwright install chromium 2>nul
)
start "" "%~dp0AI_Maketing_Facebook.exe"
"@ | Set-Content -Encoding ASCII (Join-Path $Out "CHAY_APP.cmd")

Write-Host "=== [5/5] Zip ===" -ForegroundColor Cyan
$Zip = Join-Path $Root "dist\AI_Maketing_Facebook_Windows.zip"
if (Test-Path $Zip) { Remove-Item $Zip }
Compress-Archive -Path $Out -DestinationPath $Zip -Force

# Inno Setup (nếu có)
$Iss = Join-Path $Root "packaging\setup_windows.iss"
$Iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe"
if ((Test-Path $Iss) -and (Test-Path $Iscc)) {
    Write-Host "=== Inno Setup ===" -ForegroundColor Cyan
    & $Iscc $Iss
}

Write-Host ""
Write-Host "=============================================="
Write-Host " XONG Windows"
Write-Host "  Folder: $Out"
Write-Host "  Zip:    $Zip"
Write-Host "=============================================="
Get-Item $Zip | Format-List FullName, Length
