$ErrorActionPreference = "Stop"

function Read-DotEnv($path) {
  $map = @{}
  if (!(Test-Path -LiteralPath $path)) { return $map }
  Get-Content -LiteralPath $path | ForEach-Object {
    $line = $_.Trim()
    if ($line -eq "" -or $line.StartsWith("#")) { return }
    $idx = $line.IndexOf("=")
    if ($idx -lt 1) { return }
    $k = $line.Substring(0, $idx).Trim()
    $v = $line.Substring($idx + 1).Trim()
    $map[$k] = $v
  }
  return $map
}

function Require($cond, $msg) {
  if (-not $cond) { throw $msg }
}

function Open-IfExists($path) {
  if (Test-Path -LiteralPath $path) {
    Start-Process -FilePath $path | Out-Null
    return $true
  }
  return $false
}

# bootstrap_kit folder
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $Root

# Kit root is one level up from bootstrap_kit
$KitRoot = Split-Path $Root -Parent

# Prefer kit-root .env, fallback to local bootstrap_kit/.env (if present)
$EnvPath1 = Join-Path $KitRoot ".env"
$EnvPath2 = Join-Path $Root ".env"

$envMap = Read-DotEnv $EnvPath1
if ($envMap.Count -eq 0) { $envMap = Read-DotEnv $EnvPath2 }

Require ($envMap.ContainsKey("TENANT_REF")) "TENANT_REF missing in .env. Edit the .env in the extracted kit root and try again."
Require ($envMap.ContainsKey("LICENSE_KEY")) "LICENSE_KEY missing in .env. Edit the .env in the extracted kit root and try again."

$TenantRef  = $envMap["TENANT_REF"]
$LicenseKey = $envMap["LICENSE_KEY"]

if ($TenantRef -notmatch "^t_[a-f0-9]{16}$") { throw "Invalid TENANT_REF format." }
if ([string]::IsNullOrWhiteSpace($LicenseKey)) { throw "LICENSE_KEY is empty." }

$ApiBase = "https://api.blogger.mytown.ink"
if ($envMap.ContainsKey("API_BASE_URL") -and -not [string]::IsNullOrWhiteSpace($envMap["API_BASE_URL"])) {
  $ApiBase = $envMap["API_BASE_URL"].Trim().TrimEnd("/")
}

$Endpoint = "$ApiBase/kit/package.php"

Write-Host ""
Write-Host "[Blogger Kit] TENANT_REF=$TenantRef"
Write-Host "[Blogger Kit] API=$ApiBase"
Write-Host ""

# Where to install (inside bootstrap_kit/app)
$InstallDir = Join-Path $Root "app"
$PkgOut     = Join-Path $Root "blogger-app-package.tar.gz"

# Ensure tools exist
$tar = Get-Command tar.exe -ErrorAction SilentlyContinue
Require ($tar) "tar.exe not found. You need Windows 10/11 with tar.exe (usually included)."

# Download package via POST JSON
$payload = @{ ref = $TenantRef; license = $LicenseKey } | ConvertTo-Json -Compress

try {
  $resp = Invoke-WebRequest -Uri $Endpoint -Method POST -ContentType "application/json" -Body $payload -OutFile $PkgOut -UseBasicParsing
} catch {
  if (Test-Path -LiteralPath $PkgOut) {
    $first = Get-Content -LiteralPath $PkgOut -TotalCount 12 -ErrorAction SilentlyContinue
    if ($first) {
      Write-Host "---- Server response (first lines) ----" -ForegroundColor Yellow
      $first | ForEach-Object { Write-Host $_ }
      Write-Host "--------------------------------------" -ForegroundColor Yellow
    }
  }
  throw "Package download failed. $($_.Exception.Message)"
}

# Validate file looks sane (basic size check)
$size = (Get-Item -LiteralPath $PkgOut).Length
Require ($size -gt 1024) "Downloaded package looks invalid (too small)."

# Create install dir
if (!(Test-Path -LiteralPath $InstallDir)) {
  New-Item -ItemType Directory -Path $InstallDir | Out-Null
}

Write-Host "[Blogger Kit] Extracting package to: $InstallDir"

# Extract tarball into install dir
& tar.exe -xzf $PkgOut -C $InstallDir
if ($LASTEXITCODE -ne 0) { throw "tar extraction failed." }

# Copy kit-root .env into install dir (used by the app)
$InstalledEnv = Join-Path $InstallDir ".env"
if (Test-Path -LiteralPath $EnvPath1) {
  Copy-Item -LiteralPath $EnvPath1 -Destination $InstalledEnv -Force
} elseif (Test-Path -LiteralPath $EnvPath2) {
  Copy-Item -LiteralPath $EnvPath2 -Destination $InstalledEnv -Force
}

Write-Host ""
Write-Host "Install complete."
Write-Host "Installed to: $InstallDir"
Write-Host ""

# Open installed folder and return user to Start Here page
try {
  Start-Process explorer.exe $InstallDir | Out-Null
} catch { }

# Re-open START_HERE.html so user continues to Step B (Connect WordPress)
$StartHere = Join-Path $KitRoot "START_HERE.html"
Open-IfExists $StartHere | Out-Null

Write-Host "Next (Step B):"
Write-Host " - Open START_HERE.html (it should open automatically) and continue to 'Connect WordPress'."
Write-Host " - If you want a quick test and you have PHP installed:"
Write-Host "   php .\bootstrap_kit\app\blogger-app\wp_test_post.php"
Write-Host ""
exit 0
