# Simple helper script to get structDir from project config.json
# Reads config.json from .config folder in project root

param(
    [string]$ProjectRoot
)

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

if ([string]::IsNullOrWhiteSpace($ProjectRoot)) {
    # Try to determine project root from script location
    if ($PSScriptRoot) {
        $ProjectRoot = Split-Path -Parent $PSScriptRoot
    }
    elseif ($MyInvocation.MyCommand.Path) {
        $ProjectRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
    }
    else {
        Write-Error "Unable to determine project root. Please provide -ProjectRoot parameter."
        exit 1
    }
}

$configPath = Join-Path -Path $ProjectRoot -ChildPath '.config\config.json'

if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
    Write-Error "config.json not found at: $configPath"
    exit 1
}

try {
    $config = Get-Content -LiteralPath $configPath -Raw -ErrorAction Stop | ConvertFrom-Json
    
    if ($config.PSObject.Properties.Name -contains 'structDir') {
        $structDir = $config.structDir
        if ($null -ne $structDir -and ($structDir -isnot [string] -or $structDir.Trim().Length -gt 0)) {
            # If it's an absolute path, resolve it
            if ([System.IO.Path]::IsPathRooted($structDir)) {
                $resolved = Resolve-Path -LiteralPath $structDir -ErrorAction SilentlyContinue
                if ($null -ne $resolved) {
                    Write-Output $resolved.Path
                    exit 0
                }
                Write-Output $structDir
                exit 0
            }
            # Relative path - resolve relative to config location
            $candidate = Join-Path -Path (Split-Path -Parent $configPath) -ChildPath $structDir
            $resolvedCandidate = Resolve-Path -LiteralPath $candidate -ErrorAction SilentlyContinue
            if ($null -ne $resolvedCandidate) {
                Write-Output $resolvedCandidate.Path
                exit 0
            }
            Write-Output $candidate
            exit 0
        }
    }
    
    # Default: return the directory containing config.json (project root)
    Write-Output $ProjectRoot
    exit 0
}
catch {
    Write-Error "Failed to read or parse config.json: $($_.Exception.Message)"
    exit 1
}

