# common.ps1 - shared functions for all deployment scripts
# Dot-source at the top of each script: . "$PSScriptRoot\common.ps1"
# Requires $LogFile variable set in the calling script's scope.

$ErrorActionPreference = "Continue"

function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    $line = "[$(Get-Date -Format 'HH:mm:ss')] [$Level] $Message"
    if ($LogFile) {
        $null = New-Item -ItemType Directory -Force -Path (Split-Path $LogFile -Parent) -ErrorAction SilentlyContinue
        Add-Content -Path $LogFile -Value $line -Encoding UTF8
    }
    Write-Output $line
}

function Get-Feature {
    param([object]$Cfg, [string]$StepID, [string]$FeatureID, [bool]$Default = $true)
    try {
        if ($null -eq $Cfg) { return $Default }
        $stepFeatures = $Cfg.features.$StepID
        if ($null -eq $stepFeatures) { return $Default }
        $val = $stepFeatures.$FeatureID
        if ($null -eq $val) { return $Default }
        return [bool]$val
    } catch { return $Default }
}

function Load-Config {
    param([string]$Path)
    if (-not $Path -or -not (Test-Path $Path)) {
        Write-Log "No config file at: $Path" -Level WARN
        return $null
    }
    try {
        $cfg = Get-Content $Path -Raw -Encoding UTF8 | ConvertFrom-Json
        Write-Log "Config loaded from $Path" -Level INFO
        return $cfg
    }
    catch {
        Write-Log "Failed to parse config: $_" -Level ERROR
        return $null
    }
}
