# ==============================================================================
# MORPH-SPEC - Deploy Script (PowerShell)
# Automated deployment of Azure infrastructure
# ==============================================================================

[CmdletBinding()]
param(
    [Parameter(Mandatory=$false)]
    [string]$AppName = "myapp",

    [Parameter(Mandatory=$false)]
    [ValidateSet("dev", "staging", "prod")]
    [string]$Environment = "dev",

    [Parameter(Mandatory=$false)]
    [string]$Location = "eastus",

    [Parameter(Mandatory=$false)]
    [string]$SubscriptionId,

    [Parameter(Mandatory=$false)]
    [ValidateSet("appservice", "containerapp")]
    [string]$HostingType = "appservice",

    [Parameter(Mandatory=$false)]
    [ValidateSet("F1", "B1", "S1", "P1v2")]
    [string]$AppServiceSku = "F1",

    [Parameter(Mandatory=$false)]
    [string]$ContainerImage = "mcr.microsoft.com/hello-world:latest"
)

# ==============================================================================
# CONFIGURATION
# ==============================================================================

$ErrorActionPreference = "Stop"

$ResourceGroup = "rg-$AppName-$Environment"
$DeploymentName = "deploy-$AppName-$(Get-Date -Format 'yyyyMMdd-HHmmss')"

# ==============================================================================
# FUNCTIONS
# ==============================================================================

function Write-InfoLog {
    param([string]$Message)
    Write-Host "ℹ️  $Message" -ForegroundColor Blue
}

function Write-SuccessLog {
    param([string]$Message)
    Write-Host "✅ $Message" -ForegroundColor Green
}

function Write-WarningLog {
    param([string]$Message)
    Write-Host "⚠️  $Message" -ForegroundColor Yellow
}

function Write-ErrorLog {
    param([string]$Message)
    Write-Host "❌ $Message" -ForegroundColor Red
}

function Test-Prerequisites {
    Write-InfoLog "Checking prerequisites..."

    # Check Azure CLI
    $azCliInstalled = Get-Command az -ErrorAction SilentlyContinue
    if (-not $azCliInstalled) {
        Write-ErrorLog "Azure CLI not found. Install from: https://aka.ms/azure-cli"
        exit 1
    }

    # Check login
    try {
        $null = az account show 2>$null
    }
    catch {
        Write-ErrorLog "Not logged in to Azure. Run: az login"
        exit 1
    }

    # Set subscription if provided
    if ($SubscriptionId) {
        Write-InfoLog "Setting subscription to: $SubscriptionId"
        az account set --subscription $SubscriptionId
    }

    Write-SuccessLog "Prerequisites checked"
}

function New-ResourceGroupIfNotExists {
    Write-InfoLog "Creating resource group: $ResourceGroup"

    $exists = az group exists -n $ResourceGroup
    if ($exists -eq "true") {
        Write-WarningLog "Resource group already exists"
    }
    else {
        az group create `
            --name $ResourceGroup `
            --location $Location `
            --tags `
                environment=$Environment `
                application=$AppName `
                managedBy=bicep `
                framework=morph-spec

        Write-SuccessLog "Resource group created"
    }
}

function New-SqlPassword {
    # Generate secure random password
    $bytes = New-Object byte[] 32
    [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($bytes)
    $password = [Convert]::ToBase64String($bytes) -replace '[=+/]', '' | Select-Object -First 25

    Write-SuccessLog "SQL password generated (stored in Key Vault after deploy)"
    return $password
}

function Deploy-Infrastructure {
    param([string]$SqlPassword)

    Write-InfoLog "Deploying infrastructure..."
    Write-InfoLog "  App Name: $AppName"
    Write-InfoLog "  Environment: $Environment"
    Write-InfoLog "  Hosting Type: $HostingType"
    Write-InfoLog "  Location: $Location"

    # Prepare parameters file
    $paramsFile = "parameters.$Environment.json"

    if (-not (Test-Path $paramsFile)) {
        Write-ErrorLog "Parameters file not found: $paramsFile"
        exit 1
    }

    # Deploy
    az deployment group create `
        --resource-group $ResourceGroup `
        --name $DeploymentName `
        --template-file main.bicep `
        --parameters "@$paramsFile" `
        --parameters `
            appName=$AppName `
            environment=$Environment `
            location=$Location `
            hostingType=$HostingType `
            appServiceSku=$AppServiceSku `
            containerImage=$ContainerImage `
            sqlAdminPassword=$SqlPassword `
        --output table

    Write-SuccessLog "Infrastructure deployed"
}

function Show-Outputs {
    Write-InfoLog "Retrieving deployment outputs..."

    $appUrl = az deployment group show `
        -g $ResourceGroup `
        -n $DeploymentName `
        --query properties.outputs.appUrl.value -o tsv

    $sqlConnection = az deployment group show `
        -g $ResourceGroup `
        -n $DeploymentName `
        --query properties.outputs.sqlConnectionString.value -o tsv

    $appInsightsConnection = az deployment group show `
        -g $ResourceGroup `
        -n $DeploymentName `
        --query properties.outputs.appInsightsConnectionString.value -o tsv

    Write-Host ""
    Write-Host "╔════════════════════════════════════════════════════════════════╗" -ForegroundColor Green
    Write-Host "║              DEPLOYMENT SUCCESSFUL                             ║" -ForegroundColor Green
    Write-Host "╚════════════════════════════════════════════════════════════════╝" -ForegroundColor Green
    Write-Host ""
    Write-Host "🌐 Application URL:" -ForegroundColor Cyan
    Write-Host "   $appUrl"
    Write-Host ""
    Write-Host "🗄️  SQL Connection String:" -ForegroundColor Cyan
    Write-Host "   $sqlConnection"
    Write-Host ""
    Write-Host "📊 App Insights Connection String:" -ForegroundColor Cyan
    Write-Host "   $appInsightsConnection"
    Write-Host ""
    Write-Host "💡 Next steps:" -ForegroundColor Yellow

    if ($HostingType -eq "appservice") {
        Write-Host "   1. Deploy your code: az webapp up --name app-$AppName-$Environment"
        Write-Host "   2. View logs: az webapp log tail --name app-$AppName-$Environment -g $ResourceGroup"
    }
    else {
        Write-Host "   1. Build and push container: az acr build --registry <ACR> --image ${AppName}:latest ."
        Write-Host "   2. Update container app: az containerapp update -n ca-$AppName-$Environment -g $ResourceGroup --image <IMAGE>"
        Write-Host "   3. View logs: az containerapp logs show -n ca-$AppName-$Environment -g $ResourceGroup --follow"
    }

    Write-Host ""
}

# ==============================================================================
# MAIN
# ==============================================================================

function Main {
    Write-Host ""
    Write-Host "╔════════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
    Write-Host "║          MORPH-SPEC - Azure Infrastructure Deploy             ║" -ForegroundColor Cyan
    Write-Host "╚════════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
    Write-Host ""

    Test-Prerequisites
    New-ResourceGroupIfNotExists
    $sqlPassword = New-SqlPassword
    Deploy-Infrastructure -SqlPassword $sqlPassword
    Show-Outputs

    Write-SuccessLog "Deployment complete! 🚀"
}

# Run main function
Main
