#Requires -Version 7.4

function Get-vSEALDependencyStatus {
    <#
    .SYNOPSIS
        Returns dependency status for CLI doctor command and troubleshooting.

    .DESCRIPTION
        Checks the status of all required PowerShell module dependencies
        (PSToml) and returns structured results suitable
        for JSON serialization by the CLI.

        Each dependency is checked for presence and version. Status values:
        - Installed: Module satisfies minimum version requirement
        - Outdated: Module installed but version too low or prerelease
        - Missing: Module not installed
        - Error: Check failed (includes ErrorMessage property)

    .EXAMPLE
        Get-vSEALDependencyStatus

        Returns array of dependency status objects for PSToml.

    .EXAMPLE
        Get-vSEALDependencyStatus | ConvertTo-Json -Depth 3

        Returns dependency status as JSON for CLI consumption.

    .EXAMPLE
        Get-vSEALDependencyStatus | Where-Object { $_.Status -ne 'Installed' }

        Returns only dependencies that need attention.

    .OUTPUTS
        [PSCustomObject[]] Array of dependency status objects suitable for JSON serialization.

        Each object contains:
        - Name: Module name (e.g., 'PSToml')
        - MinimumVersion: Required minimum version (e.g., '0.4.0')
        - InstalledVersion: Installed version string or $null if missing
        - Status: 'Installed', 'Outdated', 'Missing', or 'Error'
        - InstallCommand: Remediation command or $null if satisfied
        - ErrorMessage: Error details if Status = 'Error', else $null
    #>
    [CmdletBinding()]
    [OutputType([PSCustomObject[]])]
    param()

    # Define required modules with minimum versions (matches Test-ModuleDependenciesPrerequisite)
    $requiredModules = @(
        @{ Name = 'PSToml'; MinVersion = [version]'0.4.0' }
    )

    # Detect portable mode from PSModulePath shape (same logic as Test-PortableDepsMode)
    $psPaths = $env:PSModulePath -split [System.IO.Path]::PathSeparator
    $isPortable = $false
    $depsPath = $null
    if ($psPaths.Count -eq 2) {
        foreach ($p in $psPaths) {
            if ((Split-Path -Leaf $p) -eq 'deps') {
                $isPortable = $true
                $depsPath = $p
                break
            }
        }
    }

    $results = @()

    foreach ($required in $requiredModules) {
        $moduleName = $required.Name
        $minVersion = $required.MinVersion

        try {
            if ($isPortable) {
                # Portable mode: check bundled deps path directly
                $moduleManifestPath = Join-Path -Path $depsPath -ChildPath "$moduleName/$moduleName.psd1"

                if (-not (Test-Path -Path $moduleManifestPath -PathType Leaf)) {
                    # Bundled module not found
                    $results += [PSCustomObject]@{
                        Name             = $moduleName
                        MinimumVersion   = $minVersion.ToString()
                        InstalledVersion = $null
                        Status           = 'Missing'
                        InstallCommand   = "Re-extract the portable distribution or verify the deps folder is intact."
                        ErrorMessage     = $null
                    }
                }
                else {
                    # Parse version from the bundled manifest
                    $manifestData = Import-PowerShellDataFile -Path $moduleManifestPath -ErrorAction Stop
                    $bundledVersion = [version]$manifestData.ModuleVersion

                    if ($bundledVersion -lt $minVersion) {
                        $results += [PSCustomObject]@{
                            Name             = $moduleName
                            MinimumVersion   = $minVersion.ToString()
                            InstalledVersion = $bundledVersion.ToString()
                            Status           = 'Outdated'
                            InstallCommand   = "Re-extract the portable distribution."
                            ErrorMessage     = $null
                        }
                    }
                    else {
                        $results += [PSCustomObject]@{
                            Name             = $moduleName
                            MinimumVersion   = $minVersion.ToString()
                            InstalledVersion = $bundledVersion.ToString()
                            Status           = 'Installed'
                            InstallCommand   = $null
                            ErrorMessage     = $null
                        }
                    }
                }
            }
            else {
                # Dev mode: existing behavior unchanged - use Get-Module -ListAvailable
                $availableModule = Get-Module -Name $moduleName -ListAvailable -ErrorAction SilentlyContinue |
                    Sort-Object -Property Version -Descending |
                    Select-Object -First 1

                if ($null -eq $availableModule) {
                    # Module not installed
                    $results += [PSCustomObject]@{
                        Name             = $moduleName
                        MinimumVersion   = $minVersion.ToString()
                        InstalledVersion = $null
                        Status           = 'Missing'
                        InstallCommand   = "Install-Module $moduleName -MinimumVersion $($minVersion.ToString())"
                        ErrorMessage     = $null
                    }
                }
                else {
                    # Check for prerelease version
                    $prereleaseTag = $availableModule.PrivateData?.PSData?.Prerelease
                    $installedVersion = $availableModule.Version

                    if ($prereleaseTag) {
                        # Prerelease versions do not satisfy stable requirement
                        $results += [PSCustomObject]@{
                            Name             = $moduleName
                            MinimumVersion   = $minVersion.ToString()
                            InstalledVersion = "$($installedVersion.ToString())-$prereleaseTag"
                            Status           = 'Outdated'
                            InstallCommand   = "Install-Module $moduleName -MinimumVersion $($minVersion.ToString())"
                            ErrorMessage     = $null
                        }
                    }
                    elseif ($installedVersion -lt $minVersion) {
                        # Module installed but version too low
                        $results += [PSCustomObject]@{
                            Name             = $moduleName
                            MinimumVersion   = $minVersion.ToString()
                            InstalledVersion = $installedVersion.ToString()
                            Status           = 'Outdated'
                            InstallCommand   = "Update-Module $moduleName"
                            ErrorMessage     = $null
                        }
                    }
                    else {
                        # Module satisfies requirement
                        $results += [PSCustomObject]@{
                            Name             = $moduleName
                            MinimumVersion   = $minVersion.ToString()
                            InstalledVersion = $installedVersion.ToString()
                            Status           = 'Installed'
                            InstallCommand   = $null
                            ErrorMessage     = $null
                        }
                    }
                }
            }
        }
        catch {
            # Error during check - return partial result with error details
            $results += [PSCustomObject]@{
                Name             = $moduleName
                MinimumVersion   = $minVersion.ToString()
                InstalledVersion = $null
                Status           = 'Error'
                InstallCommand   = $null
                ErrorMessage     = $_.Exception.Message
            }
        }
    }

    # Ensure we always return an array (use Write-Output with -NoEnumerate to prevent unwrapping)
    Write-Output -NoEnumerate $results
}
