# Percorsi file
$envFile         = Resolve-Path -LiteralPath (Join-Path $PSScriptRoot ".." "env.json")         # JSON originale
$collectionsRoot = Resolve-Path -LiteralPath (Join-Path $PSScriptRoot ".." "autodocs/httpyac") # cartella di partenza delle collezioni

# Costanti
$API_SECTION_NAME = "API"
$ENV_TEMPLATE_FILENAME = ".env.template"
$ENV_FILENAME = ".env"

# 1. Se il file non esiste → errore
if (-not (Test-Path $envFile)) {
    Write-Error "File '$ENV_JSON_FILENAME' non trovato."
    exit 1
}

# Carica JSON mantenendo ordine
$raw = Get-Content $envFile -Raw
$data = $raw | ConvertFrom-Json -AsHashtable

if (-not $data.ContainsKey($API_SECTION_NAME)) {
    Write-Error "Il file '$ENV_JSON_FILENAME' non contiene la sezione '$API_SECTION_NAME'."
    exit 1
}

# Funzione per leggere file .env (KEY=VALUE)
function Read-EnvFile($path) {
    $result = [ordered]@{}
    foreach ($line in Get-Content $path) {
        if ($line.Trim() -eq "" -or $line.Trim().StartsWith("#")) { continue }
        if ($line -match "^\s*([^=]+)\s*=\s*(.*)$") {
            $key = $matches[1].Trim()
            $value = $matches[2]
            $result[$key] = $value
        }
    }
    return $result
}

# Funzione per scrivere file .env
function Write-EnvFile($path, $hashtable) {
    $lines = foreach ($k in $hashtable.Keys) {
        "$k=$(Format-EnvValue $hashtable[$k])"
    }
    Set-Content $path -Value $lines -Encoding UTF8
}

function Format-EnvValue($value) {
    if ($null -eq $value) {
        return ""
    }
    if ($value -match "#") {
        return "'$value'"
    }
    return $value
}

function KeysMatch($a, $b) {
    $diff = Compare-Object -ReferenceObject ($a | Sort-Object -Unique) -DifferenceObject ($b | Sort-Object -Unique)

        return -not $diff
}

# 2. Scorri tutte le sezioni sotto API
foreach ($sectionName in $data[$API_SECTION_NAME].Keys) {

    Write-Host "`n--- Sezione: $sectionName ---"

    $section = $data[$API_SECTION_NAME][$sectionName]

    # a. Verifica esistenza cartella
    $folder = Join-Path $collectionsRoot $sectionName
    if (-not (Test-Path $folder)) {
        Write-Warning "La cartella '$folder' non esiste. Sezione ignorata."
        continue
    }

    # b. Verifica .env.template
    $templatePath = Join-Path $folder $ENV_TEMPLATE_FILENAME
    if (Test-Path $templatePath) {
        $template = Read-EnvFile $templatePath

        $templateKeys = $template.Keys
        $sectionKeys = $section.Keys

        if ($templateKeys.Count -ne $sectionKeys.Count -or -not (KeysMatch $templateKeys $sectionKeys)) {
            Write-Warning "Il file '$ENV_TEMPLATE_FILENAME' in '$sectionName' non ha le stesse chiavi della sezione."
        }
    }

    # c/d/e. Gestione file .env
    $envPath = Join-Path $folder $ENV_FILENAME

    if (-not (Test-Path $envPath)) {
        # c. Genera nuovo file .env
        Write-Host "Generazione nuovo file '$ENV_FILENAME' per '$sectionName'."
        $newEnv = [ordered]@{}
        foreach ($key in $sectionKeys) {
            $newEnv[$key] = $section[$key]
        }
        Write-EnvFile $envPath $newEnv
        continue
    }

    # d. Verifica chiavi .env esistente
    $existingEnv = Read-EnvFile $envPath

    $envKeys = $existingEnv.Keys
    $sectionKeys = $section.Keys

    if ($envKeys.Count -ne $sectionKeys.Count -or -not (KeysMatch $envKeys $sectionKeys)) {
        Write-Warning "Il file '$ENV_FILENAME' in '$sectionName' non ha le stesse chiavi della sezione."
    }

    # e. Aggiorna valori
    $updatedEnv = [ordered]@{}

    foreach ($key in $section.Keys) {
        $valueFromJson = $section[$key]

        if ($existingEnv.Contains($key)) {
            if ($null -ne $valueFromJson) {
                # aggiorna
                $updatedEnv[$key] = $valueFromJson
            } else {
                # mantieni
                $updatedEnv[$key] = $existingEnv[$key]
            }
        } else {
            # chiave mancante → aggiungi
            $updatedEnv[$key] = $valueFromJson
        }
    }

    # f. Aggiungi chiavi mancanti da .env.template
    if (Test-Path $templatePath) {
        foreach ($key in $template.Keys) {
            if (-not $updatedEnv.Contains($key)) {
                Write-Host "Aggiunta chiave mancante '$key' da '$ENV_TEMPLATE_FILENAME'."
                $updatedEnv[$key] = $template[$key]
            }
        }
    }

    Write-Host "Aggiornamento file '$ENV_FILENAME' per '$sectionName'..."
    Write-EnvFile $envPath $updatedEnv
    Write-Host "File '$(Resolve-Path -LiteralPath $envPath)' aggiornato."
}

Write-Host "`nOperazione completata."
