Private/Domain/SourcePolicy.ps1

$script:sourcePolicyUses = @{
    display = @('Display')
    cache = @('Cache')
    retention = @('Retention')
    persistence = @('Cache', 'Retention')
    export = @('Redistribution')
    briefing = @('Display', 'Retention', 'CommercialUse', 'Redistribution')
    commercialUse = @('CommercialUse')
    redistribution = @('Redistribution')
}

function Get-SourcePolicyDecision {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$SourceId,

        [Parameter(Mandatory)]
        [ValidateSet('display', 'cache', 'retention', 'persistence', 'export', 'briefing', 'commercialUse', 'redistribution')]
        [string]$Use
    )

    $matches = @($Sources | Where-Object { $null -ne $_ -and $_.sourceId -eq $SourceId })
    if ($matches.Count -eq 0) {
        return [pscustomobject]@{
            allowed = $false
            reason = 'source-unknown'
            attribution = $null
        }
    }
    if ($matches.Count -ne 1) {
        return [pscustomobject]@{
            allowed = $false
            reason = 'source-identity-ambiguous'
            attribution = $null
        }
    }

    $source = $matches[0]
    $attribution = [string]$source.attribution
    if ($source.termsReviewStatus -eq 'unreviewed') {
        return [pscustomobject]@{
            allowed = $false
            reason = 'terms-unreviewed'
            attribution = $attribution
        }
    }
    if ($source.termsReviewStatus -eq 'restricted') {
        return [pscustomobject]@{
            allowed = $false
            reason = 'terms-restricted'
            attribution = $attribution
        }
    }
    if ($null -eq $source.termsReviewedAtUtc) {
        return [pscustomobject]@{
            allowed = $false
            reason = 'terms-review-date-missing'
            attribution = $attribution
        }
    }
    if ($Use -in @('display', 'export', 'briefing', 'redistribution') -and
        [string]::IsNullOrWhiteSpace($attribution)) {
        return [pscustomobject]@{
            allowed = $false
            reason = 'attribution-missing'
            attribution = $null
        }
    }

    $approvedUses = $source.approvedUses
    foreach ($requiredUse in $script:sourcePolicyUses[$Use]) {
        $right = if ($null -eq $approvedUses) {
            $null
        }
        else {
            $approvedUses.PSObject.Properties[$requiredUse]
        }

        if ($null -eq $right -or $right.Value -isnot [bool] -or -not $right.Value) {
            return [pscustomobject]@{
                allowed = $false
                reason = "right-not-approved:$requiredUse"
                attribution = $attribution
            }
        }
    }

    [pscustomobject]@{
        allowed = $true
        reason = $null
        attribution = $attribution
    }
}

function Import-SourceRightsRegister {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Path
    )

    $register = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
    if ($register.schemaVersion -ne 1 -or $null -eq $register.PSObject.Properties['sources']) {
        throw 'Source-rights register has an unsupported or incomplete schema.'
    }
    $unknownRegisterFields = @($register.PSObject.Properties.Name | Where-Object { $_ -notin @('schemaVersion', 'sources') })
    if ($unknownRegisterFields.Count -gt 0) {
        throw "Source-rights register contains unsupported fields: $($unknownRegisterFields -join ', ')."
    }
    if ($null -eq $register.sources -or $register.sources -is [string]) {
        throw 'Source-rights register sources must be an array.'
    }

    $allowedSourceFields = @(
        'sourceId', 'name', 'capabilityClass', 'attribution', 'quotaPolicy',
        'termsReviewStatus', 'termsReviewedAtUtc', 'approvedUses', 'credentialReference'
    )
    $allowedUseFields = @('Display', 'Cache', 'Retention', 'CommercialUse', 'Redistribution')
    $sourceIds = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
    $normalizedSources = [System.Collections.Generic.List[object]]::new()

    foreach ($source in @($register.sources)) {
        if ($null -eq $source -or $source -isnot [pscustomobject]) {
            throw 'Source-rights register contains an invalid source entry.'
        }

        $unknownFields = @($source.PSObject.Properties.Name | Where-Object { $_ -notin $allowedSourceFields })
        if ($unknownFields.Count -gt 0) {
            throw "Source-rights register contains unsupported source fields: $($unknownFields -join ', ')."
        }

        foreach ($requiredField in @('sourceId', 'name', 'capabilityClass', 'attribution', 'quotaPolicy', 'termsReviewStatus', 'approvedUses')) {
            if ($null -eq $source.PSObject.Properties[$requiredField] -or
                [string]::IsNullOrWhiteSpace([string]$source.$requiredField)) {
                throw "Source-rights register is missing required field '$requiredField'."
            }
        }
        if ($source.termsReviewStatus -notin @('unreviewed', 'reviewed', 'restricted')) {
            throw "Source '$($source.sourceId)' has an unsupported terms-review status."
        }
        if ($source.PSObject.Properties['credentialReference'] -and
            $null -ne $source.credentialReference -and
            [string]$source.credentialReference -notmatch '^[A-Za-z0-9._-]{1,128}$') {
            throw "Source '$($source.sourceId)' has an invalid credential reference."
        }
        if (-not $sourceIds.Add([string]$source.sourceId)) {
            throw "Source-rights register contains duplicate source ID '$($source.sourceId)'."
        }
        if ($source.termsReviewStatus -eq 'reviewed' -and $null -eq $source.termsReviewedAtUtc) {
            throw "Reviewed source '$($source.sourceId)' must include a terms-review timestamp."
        }
        if ($source.approvedUses -isnot [pscustomobject]) {
            throw "Source '$($source.sourceId)' must declare approved uses as an object."
        }

        $unknownUses = @($source.approvedUses.PSObject.Properties.Name | Where-Object { $_ -notin $allowedUseFields })
        if ($unknownUses.Count -gt 0) {
            throw "Source '$($source.sourceId)' contains unsupported rights: $($unknownUses -join ', ')."
        }

        $normalizedUses = [ordered]@{}
        foreach ($useName in $allowedUseFields) {
            $useProperty = $source.approvedUses.PSObject.Properties[$useName]
            $approved = $false
            if ($null -ne $useProperty) {
                if ($useProperty.Value -isnot [bool]) {
                    throw "Source '$($source.sourceId)' right '$useName' must be Boolean."
                }
                $approved = $useProperty.Value
            }
            if ($source.termsReviewStatus -ne 'reviewed' -and $approved) {
                throw "Source '$($source.sourceId)' cannot approve uses before terms review."
            }
            $normalizedUses[$useName] = $approved
        }

        $reviewedAt = $null
        if ($null -ne $source.termsReviewedAtUtc) {
            $reviewedAt = [DateTimeOffset]::Parse(
                [string]$source.termsReviewedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            ).ToUniversalTime()
        }

        $normalizedSources.Add([pscustomobject][ordered]@{
            sourceId = [string]$source.sourceId
            name = [string]$source.name
            capabilityClass = [string]$source.capabilityClass
            attribution = [string]$source.attribution
            quotaPolicy = [string]$source.quotaPolicy
            termsReviewStatus = [string]$source.termsReviewStatus
            termsReviewedAtUtc = $reviewedAt
            approvedUses = [pscustomobject]$normalizedUses
            credentialReference = $source.credentialReference
        })
    }

    [pscustomobject][ordered]@{
        schemaVersion = 1
        sources = @($normalizedSources)
    }
}
function ConvertTo-SourceRightsPlainReason {
    <#
    .SYNOPSIS
        Turns a source-policy reason code into short wording for unavailable panels and layers.
    #>

    param([AllowNull()][AllowEmptyString()][string]$Reason)

    switch -Regex ($Reason) {
        '^terms-unreviewed$' { return 'awaiting licence review' }
        '^terms-restricted$' { return "licence doesn't allow display" }
        '^right-not-approved:(.+)$' {
            $use = switch ($Matches[1]) {
                'Display' { 'display' }
                'Cache' { 'local caching' }
                'Retention' { 'keeping data' }
                'Redistribution' { 'bundling the data' }
                'CommercialUse' { 'commercial use' }
                default { $Matches[1].ToLowerInvariant() }
            }
            return "licence doesn't allow $use"
        }
        '^source-unknown$' { return 'source not registered' }
        default { return 'source details incomplete' }
    }
}