[CmdletBinding()]
param(
    [string]$DesignerPath = "C:\Program Files\1cv8\8.5.1.1236\bin\1cv8.exe",
    [string]$ExpectedVersion = "8.5.1.1236",
    [string]$ServerConnection = "wsr\upo_test",
    [string]$Extension = "test2",
    [Parameter(Mandatory = $true)]
    [string]$OutputDirectory
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

if (-not (Test-Path -LiteralPath $DesignerPath -PathType Leaf)) {
    throw "1C Designer executable not found: $DesignerPath"
}

$actualVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($DesignerPath).FileVersion
if ($actualVersion -ne $ExpectedVersion) {
    throw "1C Designer version mismatch: expected $ExpectedVersion, found $actualVersion"
}

$resolvedOutput = [System.IO.Path]::GetFullPath($OutputDirectory)
if (Test-Path -LiteralPath $resolvedOutput) {
    $existingItems = @(Get-ChildItem -LiteralPath $resolvedOutput -Force)
    if ($existingItems.Count -gt 0) {
        throw "Output directory must be empty: $resolvedOutput"
    }
}
else {
    New-Item -ItemType Directory -Path $resolvedOutput | Out-Null
}

$logPath = [System.IO.Path]::GetTempFileName()
try {
    $designerArguments = @(
        "DESIGNER",
        "/S", $ServerConnection,
        "/WA+",
        "/DisableStartupMessages",
        "/DisableStartupDialogs",
        "/Out", $logPath,
        "/DumpConfigToFiles", $resolvedOutput,
        "-Extension", $Extension
    )

    & $DesignerPath @designerArguments
    $designerExitCode = $LASTEXITCODE
    $designerLog = Get-Content -LiteralPath $logPath -Raw -ErrorAction SilentlyContinue
    if ($designerExitCode -ne 0) {
        $details = if ($designerLog) { $designerLog.Trim() } else { "Designer did not write a diagnostic log." }
        throw "1C Designer export failed with exit code ${designerExitCode}: $details"
    }

    $exportedFiles = @(Get-ChildItem -LiteralPath $resolvedOutput -File -Recurse)
    if ($exportedFiles.Count -eq 0) {
        $details = if ($designerLog) { $designerLog.Trim() } else { "No diagnostic log was written." }
        throw "1C Designer reported success but exported no files: $details"
    }

    [pscustomobject]@{
        status = "exported"
        designer_version = $actualVersion
        server_connection = $ServerConnection
        extension = $Extension
        output_directory = $resolvedOutput
        exported_files = $exportedFiles.Count
        access_mode = "operating_system_integrated"
    } | ConvertTo-Json -Depth 3
}
finally {
    if (Test-Path -LiteralPath $logPath -PathType Leaf) {
        Remove-Item -LiteralPath $logPath -Force
    }
}
