#Requires -RunAsAdministrator
<#
.SYNOPSIS
  Create an IIS application + app pool for a deployed Flask app under /apps/<slug>.
#>
param(
    [Parameter(Mandatory = $true)][string]$SiteName,
    [Parameter(Mandatory = $true)][string]$AppPoolName,
    [Parameter(Mandatory = $true)][string]$AppPath,
    [Parameter(Mandatory = $true)][string]$PhysicalPath
)

$ErrorActionPreference = "Stop"
Import-Module WebAdministration

$PhysicalPath = (Resolve-Path $PhysicalPath).Path
# Normalize AppPath to start with /
if (-not $AppPath.StartsWith("/")) { $AppPath = "/$AppPath" }

Write-Host "Provisioning $AppPath -> $PhysicalPath (pool $AppPoolName)"

if (-not (Test-Path "IIS:\AppPools\$AppPoolName")) {
    New-WebAppPool -Name $AppPoolName | Out-Null
}
Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name managedRuntimeVersion -Value ""
Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name startMode -Value "AlwaysRunning"

$siteApp = "IIS:\Sites\$SiteName$AppPath"
# Remove existing application if present
$existing = Get-WebApplication -Site $SiteName -Name $AppPath.TrimStart("/") -ErrorAction SilentlyContinue
if ($existing) {
    Remove-WebApplication -Site $SiteName -Name $AppPath.TrimStart("/")
}

# App name for nested path "apps/slug" — IIS wants relative name without leading slash
$appName = $AppPath.TrimStart("/")
New-WebApplication -Site $SiteName -Name $appName -PhysicalPath $PhysicalPath -ApplicationPool $AppPoolName | Out-Null

Restart-WebAppPool -Name $AppPoolName
Write-Host "Provisioned $appName successfully."
