Private/Providers/MarketHistoryProvider.ps1

function Get-FrankfurterHistoricalCoverage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    if ($Instrument.assetClass -ne 'forex') {
        throw "Frankfurter ECB reference history does not support asset class '$($Instrument.assetClass)'."
    }
    if ([string]$Instrument.providerSymbol -notmatch '^(?<base>[A-Za-z]{3})/(?<quote>[A-Za-z]{3})$') {
        throw 'Frankfurter requires an explicit provider symbol in BASE/QUOTE form.'
    }
    $baseCurrency = $Matches.base.ToUpperInvariant()
    $quoteCurrency = $Matches.quote.ToUpperInvariant()
    if ($baseCurrency -ne 'EUR') {
        throw 'The ECB reference adapter supports only directly published EUR-base pairs.'
    }
    if ($quoteCurrency -ne $Instrument.quoteCurrency) {
        throw 'The provider-symbol quote currency does not match the normalized instrument.'
    }
    if ($Instrument.sourceIds -notcontains 'frankfurter') {
        throw 'The instrument does not declare Frankfurter as an eligible source.'
    }

    $apiSources = @($Sources | Where-Object sourceId -eq 'frankfurter')
    $dataSources = @($Sources | Where-Object sourceId -eq 'ecb-reference-rates')
    if ($apiSources.Count -ne 1 -or $dataSources.Count -ne 1) {
        throw 'Frankfurter API and ECB reference-rate rights must each have one unambiguous source-register entry.'
    }
    foreach ($source in @($apiSources[0], $dataSources[0])) {
        $displayDecision = Get-SourcePolicyDecision -Sources @($source) `
            -SourceId $source.sourceId -Use display
        $persistenceDecision = Get-SourcePolicyDecision -Sources @($source) `
            -SourceId $source.sourceId -Use persistence
        if (-not $displayDecision.allowed -or -not $persistenceDecision.allowed) {
            throw "Historical capability lookup blocked because source '$($source.sourceId)' rights do not permit display and persistence."
        }
    }

    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    $query = "base=$([uri]::EscapeDataString($baseCurrency))&quotes=$([uri]::EscapeDataString($quoteCurrency))&providers=ECB"
    $requestUri = "https://api.frankfurter.dev/v2/coverage?$query"
    if (-not $Transport) {
        $Transport = {
            param($Uri, $RequestTimeoutSeconds, $Token)
            Assert-ProviderRequestActive -CancellationToken $Token
            Invoke-RestMethod -Uri $Uri -Method Get -TimeoutSec $RequestTimeoutSeconds `
                -Headers @{ Accept = 'application/json' } -ErrorAction Stop
        }
    }
    $response = @(& $Transport $requestUri $TimeoutSeconds $CancellationToken)
    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    if ($response.Count -ne 1) {
        throw 'Frankfurter returned an invalid coverage response.'
    }
    $coverage = $response[0]
    foreach ($field in @('base', 'quotes', 'providers', 'start_date', 'end_date')) {
        if ($null -eq $coverage.PSObject.Properties[$field]) {
            throw "Frankfurter coverage is missing required field '$field'."
        }
    }
    if ([string]$coverage.base -ne $baseCurrency -or
        @($coverage.quotes) -notcontains $quoteCurrency -or
        @($coverage.providers) -notcontains 'ECB') {
        throw 'Frankfurter coverage identity does not match the requested ECB currency pair.'
    }

    $historyStartUtc = $null
    $historyEndUtc = $null
    $reason = $null
    if ([string]::IsNullOrWhiteSpace([string]$coverage.start_date) -or
        [string]::IsNullOrWhiteSpace([string]$coverage.end_date)) {
        $reason = 'The ECB provider has no queryable history for this currency pair.'
    }
    else {
        $startDate = [DateTime]::MinValue
        $endDate = [DateTime]::MinValue
        $validStart = [DateTime]::TryParseExact(
            [string]$coverage.start_date, 'yyyy-MM-dd',
            [System.Globalization.CultureInfo]::InvariantCulture,
            [System.Globalization.DateTimeStyles]::None, [ref]$startDate
        )
        $validEnd = [DateTime]::TryParseExact(
            [string]$coverage.end_date, 'yyyy-MM-dd',
            [System.Globalization.CultureInfo]::InvariantCulture,
            [System.Globalization.DateTimeStyles]::None, [ref]$endDate
        )
        if (-not $validStart -or -not $validEnd -or $startDate -gt $endDate) {
            throw 'Frankfurter returned invalid pair-coverage bounds.'
        }
        $historyStartUtc = [DateTimeOffset]::new(
            $startDate.Year, $startDate.Month, $startDate.Day, 0, 0, 0, [TimeSpan]::Zero
        )
        $historyEndUtc = [DateTimeOffset]::new(
            $endDate.Year, $endDate.Month, $endDate.Day, 23, 59, 59, [TimeSpan]::Zero
        )
    }

    [pscustomobject][ordered]@{
        InstrumentId = $Instrument.instrumentId
        SourceId = 'frankfurter'
        UpstreamSourceIds = @('ecb-reference-rates')
        ProviderKey = 'ECB'
        BaseCurrency = $baseCurrency
        QuoteCurrency = $quoteCurrency
        Intervals = @('1d')
        HistoryStartUtc = $historyStartUtc
        HistoryEndUtc = $historyEndUtc
        IsSupported = [string]::IsNullOrWhiteSpace($reason)
        Reason = $reason
        RetrievedAtUtc = $RetrievedAtUtc.ToUniversalTime()
    }
}

function Get-FrankfurterHistoricalRates {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Request,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Capability,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    if (-not $Request.isSupported) {
        throw "Historical range is unsupported: $($Request.reason)"
    }
    if ($Request.interval -ne '1d') {
        throw 'Frankfurter ECB reference history supports daily observations only.'
    }
    if ($Instrument.assetClass -ne 'forex') {
        throw "Frankfurter ECB reference history does not support asset class '$($Instrument.assetClass)'."
    }

    $providerSymbol = [string]$Instrument.providerSymbol
    if ($providerSymbol -notmatch '^(?<base>[A-Za-z]{3})/(?<quote>[A-Za-z]{3})$') {
        throw 'Frankfurter requires an explicit provider symbol in BASE/QUOTE form.'
    }
    $baseCurrency = $Matches.base.ToUpperInvariant()
    $quoteCurrency = $Matches.quote.ToUpperInvariant()
    if ($baseCurrency -ne 'EUR') {
        throw 'The ECB reference adapter supports only directly published EUR-base pairs.'
    }
    if ($quoteCurrency -ne $Instrument.quoteCurrency) {
        throw 'The provider-symbol quote currency does not match the normalized instrument.'
    }
    if ($Instrument.sourceIds -notcontains 'frankfurter') {
        throw 'The instrument does not declare Frankfurter as an eligible source.'
    }

    $frankfurterSources = @($Sources | Where-Object sourceId -eq 'frankfurter')
    $ecbSources = @($Sources | Where-Object sourceId -eq 'ecb-reference-rates')
    if ($frankfurterSources.Count -ne 1 -or $ecbSources.Count -ne 1) {
        throw 'Frankfurter API and ECB reference-rate rights must each have one unambiguous source-register entry.'
    }
    $apiSource = $frankfurterSources[0]
    $rightsSources = @($apiSource, $ecbSources[0])
    foreach ($source in $rightsSources) {
        $displayDecision = Get-SourcePolicyDecision -Sources @($source) `
            -SourceId $source.sourceId -Use display
        $persistenceDecision = Get-SourcePolicyDecision -Sources @($source) `
            -SourceId $source.sourceId -Use persistence
        if (-not $displayDecision.allowed -or -not $persistenceDecision.allowed) {
            throw "Historical retrieval blocked because source '$($source.sourceId)' rights do not permit display and persistence."
        }
    }

    $capabilities = New-ProviderCapabilities -Source $apiSource `
        -SupportedInstrumentIds @($Instrument.instrumentId) `
        -Intervals @('1d') -HistoryDepth 'Pair coverage is date- and provider-dependent.'
    if (-not (Test-ProviderCapability -Capabilities $capabilities `
            -InstrumentId $Instrument.instrumentId -Interval $Request.interval -Use display)) {
        throw 'The requested instrument or interval is not declared by the Frankfurter adapter.'
    }
    if (-not $Capability.IsSupported -or
        $Capability.InstrumentId -ne $Instrument.instrumentId -or
        $Capability.SourceId -ne 'frankfurter' -or
        'ecb-reference-rates' -notin @($Capability.UpstreamSourceIds) -or
        '1d' -notin @($Capability.Intervals)) {
        throw 'No verified Frankfurter ECB history capability exists for this instrument.'
    }
    if ($Request.startUtc -lt $Capability.HistoryStartUtc -or
        $Request.endUtc -gt $Capability.HistoryEndUtc) {
        throw 'Requested dates are outside the verified Frankfurter ECB pair coverage.'
    }

    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    $startDate = $Request.startUtc.ToUniversalTime().ToString(
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    $endDate = $Request.endUtc.ToUniversalTime().ToString(
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    $query = @(
        "from=$([uri]::EscapeDataString($startDate))"
        "to=$([uri]::EscapeDataString($endDate))"
        "base=$([uri]::EscapeDataString($baseCurrency))"
        "quotes=$([uri]::EscapeDataString($quoteCurrency))"
        'providers=ECB'
    ) -join '&'
    $requestUri = "https://api.frankfurter.dev/v2/rates?$query"
    if (-not $Transport) {
        $Transport = {
            param($Uri, $RequestTimeoutSeconds, $Token)
            Assert-ProviderRequestActive -CancellationToken $Token
            Invoke-RestMethod -Uri $Uri -Method Get -TimeoutSec $RequestTimeoutSeconds `
                -Headers @{ Accept = 'application/json' } -ErrorAction Stop
        }
    }

    $payload = @(& $Transport $requestUri $TimeoutSeconds $CancellationToken)
    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    $observations = [System.Collections.Generic.List[object]]::new()
    $seenDates = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
    foreach ($record in $payload) {
        if ($null -eq $record -or
            $null -eq $record.PSObject.Properties['date'] -or
            $null -eq $record.PSObject.Properties['base'] -or
            $null -eq $record.PSObject.Properties['quote'] -or
            $null -eq $record.PSObject.Properties['rate']) {
            throw 'Frankfurter returned a rate record with an invalid schema.'
        }

        $recordBase = ([string]$record.base).ToUpperInvariant()
        $recordQuote = ([string]$record.quote).ToUpperInvariant()
        if ($recordBase -eq $baseCurrency -and $recordQuote -eq $baseCurrency) {
            continue
        }
        if ($recordBase -ne $baseCurrency -or $recordQuote -ne $quoteCurrency) {
            throw 'Frankfurter returned an unexpected currency pair.'
        }

        $dateText = [string]$record.date
        $parsedDate = [DateTime]::MinValue
        $validDate = [DateTime]::TryParseExact(
            $dateText,
            'yyyy-MM-dd',
            [System.Globalization.CultureInfo]::InvariantCulture,
            [System.Globalization.DateTimeStyles]::None,
            [ref]$parsedDate
        )
        if (-not $validDate) {
            throw 'Frankfurter returned an invalid observation date.'
        }
        $observationDateUtc = [DateTimeOffset]::new(
            $parsedDate.Year, $parsedDate.Month, $parsedDate.Day, 0, 0, 0,
            [TimeSpan]::Zero
        )
        if ($observationDateUtc -lt $Request.startUtc.ToUniversalTime().Date -or
            $observationDateUtc -gt $Request.endUtc.ToUniversalTime().Date) {
            throw 'Frankfurter returned a rate outside the requested date range.'
        }
        if (-not $seenDates.Add($dateText)) {
            throw 'Frankfurter returned duplicate rates for a currency pair and date.'
        }

        $rate = [decimal]0
        $validRate = [decimal]::TryParse(
            [string]$record.rate,
            [System.Globalization.NumberStyles]::Number,
            [System.Globalization.CultureInfo]::InvariantCulture,
            [ref]$rate
        )
        if (-not $validRate -or $rate -le [decimal]0) {
            throw 'Frankfurter returned a non-positive or invalid exchange rate.'
        }

        $observation = New-MarketObservation -InstrumentId $Instrument.instrumentId `
            -SourceId $apiSource.sourceId -ObservedAtUtc $observationDateUtc `
            -RetrievedAtUtc $RetrievedAtUtc -Interval '1d' -Value $rate `
            -Currency $quoteCurrency -Unit $Instrument.unit -Freshness delayed
        Add-Member -InputObject $observation -NotePropertyName timestampPrecision `
            -NotePropertyValue 'date'
        Add-Member -InputObject $observation -NotePropertyName upstreamSourceId `
            -NotePropertyValue 'ecb-reference-rates'
        $observations.Add($observation)
    }

    $orderedObservations = @($observations | Sort-Object observedAtUtc)
    $sourceTimestampUtc = if ($orderedObservations.Count -gt 0) {
        $orderedObservations[-1].observedAtUtc
    }
    else {
        $null
    }
    $warnings = @(
        'ECB observations are date-only; UTC midnight is a date anchor, not a publication time.'
        'ECB reference rates are daily information rates and are not intraday prices or transaction rates.'
    )
    $emptyReason = if ($orderedObservations.Count -eq 0) { 'no-data' } else { $null }
    $resultParameters = @{
        Capabilities = $capabilities
        RequestedUse = 'display'
        RetrievedAtUtc = $RetrievedAtUtc
        SourceTimestampUtc = $sourceTimestampUtc
        Freshness = if ($emptyReason) { 'unavailable' } else { 'delayed' }
        Records = $orderedObservations
        Warnings = $warnings
    }
    if ($emptyReason) {
        $resultParameters.EmptyResultReason = $emptyReason
    }
    $result = New-ProviderResult @resultParameters
    Add-Member -InputObject $result -NotePropertyName upstreamSourceId `
        -NotePropertyValue 'ecb-reference-rates'
    Add-Member -InputObject $result -NotePropertyName upstreamSourceName `
        -NotePropertyValue $ecbSources[0].name
    $result
}

function Assert-EcbHistoryRights {
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources
    )

    $ecbSources = @($Sources | Where-Object sourceId -eq 'ecb-reference-rates')
    if ($ecbSources.Count -ne 1) {
        throw 'ECB historical rights require one unambiguous source-register entry.'
    }

    $source = $ecbSources[0]
    foreach ($use in @('display', 'persistence')) {
        $decision = Get-SourcePolicyDecision -Sources @($source) `
            -SourceId $source.sourceId -Use $use
        if (-not $decision.allowed) {
            throw "ECB historical retrieval blocked because source '$($source.sourceId)' rights do not permit display and persistence."
        }
    }
    $source
}

function Get-EcbSeriesIdentity {
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument
    )

    if ($Instrument.assetClass -ne 'forex') {
        throw "ECB reference history does not support asset class '$($Instrument.assetClass)'."
    }
    if ([string]$Instrument.providerSymbol -notmatch '^(?<base>[A-Za-z]{3})/(?<quote>[A-Za-z]{3})$') {
        throw 'ECB requires an explicit provider symbol in BASE/QUOTE form.'
    }

    $baseCurrency = $Matches.base.ToUpperInvariant()
    $quoteCurrency = $Matches.quote.ToUpperInvariant()
    if ($baseCurrency -ne 'EUR' -or $quoteCurrency -eq 'EUR') {
        throw 'The ECB reference adapter supports only directly published EUR-base currency pairs.'
    }
    if ($quoteCurrency -ne $Instrument.quoteCurrency) {
        throw 'The provider-symbol quote currency does not match the normalized instrument.'
    }
    if ($Instrument.sourceIds -notcontains 'ecb-reference-rates') {
        throw 'The instrument does not declare ECB as an eligible source.'
    }

    [pscustomobject]@{
        BaseCurrency = $baseCurrency
        QuoteCurrency = $quoteCurrency
        SeriesKey = "D.$quoteCurrency.EUR.SP00.A"
    }
}

function ConvertFrom-EcbHistoricalCsv {
    param(
        [Parameter(Mandatory)]
        [AllowEmptyString()]
        [string]$Csv,

        [Parameter(Mandatory)]
        [string]$SeriesKey,

        [Parameter(Mandatory)]
        [string]$QuoteCurrency
    )

    if ([string]::IsNullOrWhiteSpace($Csv)) {
        throw 'ECB returned an empty CSV payload.'
    }

    $normalizedCsv = $Csv.TrimStart([char]0xFEFF)
    $headerLine = ($normalizedCsv -split '\r?\n', 2)[0]
    $headers = @($headerLine -split ',')
    foreach ($requiredHeader in @(
        'KEY', 'FREQ', 'CURRENCY', 'CURRENCY_DENOM', 'EXR_TYPE',
        'EXR_SUFFIX', 'TIME_PERIOD', 'OBS_VALUE'
    )) {
        if ($requiredHeader -notin $headers) {
            throw "ECB CSV is missing required field '$requiredHeader'."
        }
    }

    $rows = @($normalizedCsv | ConvertFrom-Csv -ErrorAction Stop)
    $parsedRows = [System.Collections.Generic.List[object]]::new()
    $seenDates = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
    # The live ECB API prefixes KEY with the dataflow id (EXR.D.USD.EUR.SP00.A).
    $acceptedKeys = @($SeriesKey, "EXR.$SeriesKey")
    foreach ($row in $rows) {
        if ([string]$row.KEY -cnotin $acceptedKeys -or
            [string]$row.FREQ -ne 'D' -or
            ([string]$row.CURRENCY).ToUpperInvariant() -ne $QuoteCurrency -or
            ([string]$row.CURRENCY_DENOM).ToUpperInvariant() -ne 'EUR' -or
            [string]$row.EXR_TYPE -ne 'SP00' -or
            [string]$row.EXR_SUFFIX -ne 'A') {
            throw 'ECB returned a record for an unexpected series.'
        }

        $dateText = [string]$row.TIME_PERIOD
        $parsedDate = [DateTime]::MinValue
        if (-not [DateTime]::TryParseExact(
                $dateText,
                'yyyy-MM-dd',
                [System.Globalization.CultureInfo]::InvariantCulture,
                [System.Globalization.DateTimeStyles]::None,
                [ref]$parsedDate
            )) {
            throw 'ECB returned an invalid observation date.'
        }
        if (-not $seenDates.Add($dateText)) {
            throw 'ECB returned duplicate rates for a currency pair and date.'
        }

        $rate = [decimal]0
        if (-not [decimal]::TryParse(
                [string]$row.OBS_VALUE,
                [System.Globalization.NumberStyles]::Number,
                [System.Globalization.CultureInfo]::InvariantCulture,
                [ref]$rate
            ) -or $rate -le [decimal]0) {
            throw 'ECB returned a non-positive or invalid exchange rate.'
        }

        $parsedRows.Add([pscustomobject]@{
            DateText = $dateText
            DateUtc = [DateTimeOffset]::new(
                $parsedDate.Year, $parsedDate.Month, $parsedDate.Day, 0, 0, 0,
                [TimeSpan]::Zero
            )
            Rate = $rate
        })
    }
    @($parsedRows)
}

function Get-EcbHistoricalCoverage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    $source = Assert-EcbHistoryRights -Sources $Sources
    $identity = Get-EcbSeriesIdentity -Instrument $Instrument
    if (-not $Transport) {
        $Transport = {
            param($Uri, $RequestTimeoutSeconds, $Token)
            Assert-ProviderRequestActive -CancellationToken $Token
            $response = Invoke-WebRequest -Uri $Uri -Method Get `
                -TimeoutSec $RequestTimeoutSeconds -Headers @{ Accept = 'text/csv' } `
                -ErrorAction Stop
            [string]$response.Content
        }
    }

    $bounds = [System.Collections.Generic.List[object]]::new()
    foreach ($observationParameter in @('firstNObservations', 'lastNObservations')) {
        Assert-ProviderRequestActive -CancellationToken $CancellationToken
        $query = @(
            'format=csvdata'
            'detail=dataonly'
            "$observationParameter=1"
        ) -join '&'
        $requestUri = "https://data-api.ecb.europa.eu/service/data/EXR/$($identity.SeriesKey)?$query"
        $response = @(& $Transport $requestUri $TimeoutSeconds $CancellationToken)
        Assert-ProviderRequestActive -CancellationToken $CancellationToken
        if ($response.Count -ne 1 -or $response[0] -isnot [string]) {
            throw 'ECB returned an invalid coverage response.'
        }

        $observations = @(ConvertFrom-EcbHistoricalCsv -Csv $response[0] `
            -SeriesKey $identity.SeriesKey -QuoteCurrency $identity.QuoteCurrency)
        if ($observations.Count -eq 0) {
            $reason = 'The ECB provider has no queryable history for this currency pair.'
            return [pscustomobject][ordered]@{
                InstrumentId = $Instrument.instrumentId
                SourceId = $source.sourceId
                UpstreamSourceIds = @()
                BaseCurrency = $identity.BaseCurrency
                QuoteCurrency = $identity.QuoteCurrency
                Intervals = @('1d')
                HistoryStartUtc = $null
                HistoryEndUtc = $null
                IsSupported = $false
                Reason = $reason
                RetrievedAtUtc = $RetrievedAtUtc.ToUniversalTime()
            }
        }
        if ($observations.Count -ne 1) {
            throw 'ECB returned an invalid observation count for a coverage query.'
        }
        $bounds.Add($observations[0])
    }

    $startUtc = $bounds[0].DateUtc
    $endDate = $bounds[1].DateUtc
    if ($startUtc -gt $endDate) {
        throw 'ECB returned invalid pair-coverage bounds.'
    }
    $endUtc = $endDate.AddDays(1).AddSeconds(-1)

    [pscustomobject][ordered]@{
        InstrumentId = $Instrument.instrumentId
        SourceId = $source.sourceId
        UpstreamSourceIds = @()
        BaseCurrency = $identity.BaseCurrency
        QuoteCurrency = $identity.QuoteCurrency
        Intervals = @('1d')
        HistoryStartUtc = $startUtc
        HistoryEndUtc = $endUtc
        IsSupported = $true
        Reason = $null
        RetrievedAtUtc = $RetrievedAtUtc.ToUniversalTime()
    }
}

function Get-EcbHistoricalRates {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Request,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Capability,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    if (-not $Request.isSupported) {
        throw "Historical range is unsupported: $($Request.reason)"
    }
    if ($Request.interval -ne '1d') {
        throw 'ECB reference history supports daily observations only.'
    }

    $source = Assert-EcbHistoryRights -Sources $Sources
    $identity = Get-EcbSeriesIdentity -Instrument $Instrument
    $capabilities = New-ProviderCapabilities -Source $source `
        -SupportedInstrumentIds @($Instrument.instrumentId) `
        -Intervals @('1d') -HistoryDepth 'Direct ECB daily observations; pair coverage is discovered from the first and last observations.'
    if (-not (Test-ProviderCapability -Capabilities $capabilities `
            -InstrumentId $Instrument.instrumentId -Interval $Request.interval -Use display)) {
        throw 'The requested instrument or interval is not declared by the ECB adapter.'
    }
    if (-not $Capability.IsSupported -or
        $Capability.InstrumentId -ne $Instrument.instrumentId -or
        $Capability.SourceId -ne 'ecb-reference-rates' -or
        '1d' -notin @($Capability.Intervals) -or
        $Capability.BaseCurrency -ne $identity.BaseCurrency -or
        $Capability.QuoteCurrency -ne $identity.QuoteCurrency) {
        throw 'No verified direct ECB history capability exists for this instrument.'
    }
    if ($Request.sourceId -ne $source.sourceId) {
        throw 'The historical range source does not match the direct ECB adapter.'
    }
    if ($Request.startUtc -lt $Capability.HistoryStartUtc -or
        $Request.endUtc -gt $Capability.HistoryEndUtc) {
        throw 'Requested dates are outside the verified ECB pair coverage.'
    }

    $startDate = $Request.startUtc.ToUniversalTime().ToString(
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    $endDate = $Request.endUtc.ToUniversalTime().ToString(
        'yyyy-MM-dd',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    $query = @(
        'format=csvdata'
        'detail=dataonly'
        "startPeriod=$([uri]::EscapeDataString($startDate))"
        "endPeriod=$([uri]::EscapeDataString($endDate))"
    ) -join '&'
    $requestUri = "https://data-api.ecb.europa.eu/service/data/EXR/$($identity.SeriesKey)?$query"
    if (-not $Transport) {
        $Transport = {
            param($Uri, $RequestTimeoutSeconds, $Token)
            Assert-ProviderRequestActive -CancellationToken $Token
            $response = Invoke-WebRequest -Uri $Uri -Method Get `
                -TimeoutSec $RequestTimeoutSeconds -Headers @{ Accept = 'text/csv' } `
                -ErrorAction Stop
            [string]$response.Content
        }
    }

    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    $payload = @(& $Transport $requestUri $TimeoutSeconds $CancellationToken)
    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    if ($payload.Count -ne 1 -or $payload[0] -isnot [string]) {
        throw 'ECB returned an invalid rate response.'
    }

    $rawObservations = @(ConvertFrom-EcbHistoricalCsv -Csv $payload[0] `
        -SeriesKey $identity.SeriesKey -QuoteCurrency $identity.QuoteCurrency)
    $requestedStartDate = $Request.startUtc.ToUniversalTime().UtcDateTime.Date
    $requestedEndDate = $Request.endUtc.ToUniversalTime().UtcDateTime.Date
    $observations = [System.Collections.Generic.List[object]]::new()
    foreach ($rawObservation in $rawObservations) {
        if ($rawObservation.DateUtc.UtcDateTime.Date -lt $requestedStartDate -or
            $rawObservation.DateUtc.UtcDateTime.Date -gt $requestedEndDate) {
            throw 'ECB returned a rate outside the requested date range.'
        }
        $observation = New-MarketObservation -InstrumentId $Instrument.instrumentId `
            -SourceId $source.sourceId -ObservedAtUtc $rawObservation.DateUtc `
            -RetrievedAtUtc $RetrievedAtUtc -Interval '1d' -Value $rawObservation.Rate `
            -Currency $identity.QuoteCurrency -Unit $Instrument.unit -Freshness delayed
        Add-Member -InputObject $observation -NotePropertyName timestampPrecision `
            -NotePropertyValue 'date'
        $observations.Add($observation)
    }

    $orderedObservations = @($observations | Sort-Object observedAtUtc)
    $sourceTimestampUtc = if ($orderedObservations.Count -gt 0) {
        $orderedObservations[-1].observedAtUtc
    }
    else {
        $null
    }
    $warnings = @(
        'ECB observations are date-only; UTC midnight is a date anchor, not a publication time.'
        'ECB reference rates are daily information rates and are not intraday prices or transaction rates.'
    )
    $emptyReason = if ($orderedObservations.Count -eq 0) { 'no-data' } else { $null }
    $resultParameters = @{
        Capabilities = $capabilities
        RequestedUse = 'display'
        RetrievedAtUtc = $RetrievedAtUtc
        SourceTimestampUtc = $sourceTimestampUtc
        Freshness = if ($emptyReason) { 'unavailable' } else { 'delayed' }
        Records = $orderedObservations
        Warnings = $warnings
    }
    if ($emptyReason) {
        $resultParameters.EmptyResultReason = $emptyReason
    }
    New-ProviderResult @resultParameters
}

function Assert-FredHistoryRights {
    param(
        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources
    )

    $fredSources = @($Sources | Where-Object sourceId -eq 'fred')
    if ($fredSources.Count -ne 1) {
        throw 'FRED historical rights require one unambiguous source-register entry.'
    }
    $source = $fredSources[0]
    foreach ($use in @('display', 'persistence')) {
        $decision = Get-SourcePolicyDecision -Sources @($source) -SourceId $source.sourceId -Use $use
        if (-not $decision.allowed) {
            throw "FRED historical retrieval blocked because source '$($source.sourceId)' rights do not permit display and persistence."
        }
    }
    $source
}

function Get-FredSeriesId {
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument
    )

    if ($Instrument.sourceIds -notcontains 'fred') {
        throw 'The instrument does not declare FRED as an eligible source.'
    }
    if ([string]$Instrument.providerSymbol -notmatch '^[A-Z0-9]{2,30}$') {
        throw 'FRED requires an explicit series ID as the provider symbol.'
    }
    [string]$Instrument.providerSymbol
}

function Invoke-FredHistoryRequest {
    param(
        [Parameter(Mandatory)][string]$Path,
        [Parameter(Mandatory)][string]$Query,
        [Parameter(Mandatory)][string]$ApiKey,
        [scriptblock]$Transport,
        [int]$TimeoutSeconds,
        [System.Threading.CancellationToken]$CancellationToken
    )

    if (-not $Transport) {
        $Transport = {
            param($Uri, $RequestTimeoutSeconds, $Token)
            Assert-ProviderRequestActive -CancellationToken $Token
            Invoke-RestMethod -Uri $Uri -Method Get -TimeoutSec $RequestTimeoutSeconds `
                -UserAgent 'PSExchangeClock (personal desktop dashboard)' -ErrorAction Stop
        }
    }
    $uri = "https://api.stlouisfed.org/fred/$Path`?$Query&api_key=$([uri]::EscapeDataString($ApiKey))&file_type=json"
    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    try {
        $response = & $Transport $uri $TimeoutSeconds $CancellationToken
    }
    catch {
        # Request errors can echo the URL; never let the user's key reach the status bar or logs.
        $message = ([string]$_.Exception.Message).Replace($ApiKey, '[redacted]').Replace([uri]::EscapeDataString($ApiKey), '[redacted]')
        throw "FRED request failed: $message"
    }
    Assert-ProviderRequestActive -CancellationToken $CancellationToken
    $response
}

function Get-FredHistoricalCoverage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

        [Parameter()]
        [AllowEmptyString()]
        [AllowNull()]
        [string]$ApiKey,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    $source = Assert-FredHistoryRights -Sources $Sources
    $seriesId = Get-FredSeriesId -Instrument $Instrument
    $capability = [pscustomobject][ordered]@{
        InstrumentId = $Instrument.instrumentId
        SourceId = $source.sourceId
        UpstreamSourceIds = @()
        SeriesId = $seriesId
        Intervals = @('1d')
        HistoryStartUtc = $null
        HistoryEndUtc = $null
        IsSupported = $false
        Reason = $null
        RetrievedAtUtc = $RetrievedAtUtc.ToUniversalTime()
    }
    if ([string]::IsNullOrWhiteSpace($ApiKey)) {
        $capability.Reason = 'Enter a free FRED API key in Settings to load this history.'
        return $capability
    }

    $response = Invoke-FredHistoryRequest -Path 'series' -Query "series_id=$([uri]::EscapeDataString($seriesId))" `
        -ApiKey $ApiKey -Transport $Transport -TimeoutSeconds $TimeoutSeconds -CancellationToken $CancellationToken
    $series = @($response.seriess)
    if ($series.Count -ne 1 -or [string]$series[0].id -ne $seriesId) {
        throw 'FRED returned metadata for an unexpected series.'
    }
    $culture = [System.Globalization.CultureInfo]::InvariantCulture
    $start = [DateTime]::MinValue
    $end = [DateTime]::MinValue
    if (-not [DateTime]::TryParseExact([string]$series[0].observation_start, 'yyyy-MM-dd', $culture,
            [System.Globalization.DateTimeStyles]::None, [ref]$start) -or
        -not [DateTime]::TryParseExact([string]$series[0].observation_end, 'yyyy-MM-dd', $culture,
            [System.Globalization.DateTimeStyles]::None, [ref]$end) -or $start -gt $end) {
        throw 'FRED returned invalid series coverage dates.'
    }
    $capability.HistoryStartUtc = [DateTimeOffset]::new($start, [TimeSpan]::Zero)
    $capability.HistoryEndUtc = [DateTimeOffset]::new($end.AddDays(1).AddSeconds(-1), [TimeSpan]::Zero)
    $capability.IsSupported = $true
    $capability
}

function Get-FredHistoricalRates {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Request,

        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Capability,

        [Parameter(Mandatory)]
        [AllowEmptyCollection()]
        [object[]]$Sources,

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

        [Parameter(Mandatory)]
        [DateTimeOffset]$RetrievedAtUtc,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [System.Threading.CancellationToken]$CancellationToken = [System.Threading.CancellationToken]::None,

        [Parameter()]
        [ValidateRange(1, 120)]
        [int]$TimeoutSeconds = 20
    )

    if (-not $Request.isSupported) {
        throw "Historical range is unsupported: $($Request.reason)"
    }
    $source = Assert-FredHistoryRights -Sources $Sources
    $seriesId = Get-FredSeriesId -Instrument $Instrument
    if (-not $Capability.IsSupported -or $Capability.InstrumentId -ne $Instrument.instrumentId -or
        $Capability.SourceId -ne 'fred' -or $Capability.SeriesId -ne $seriesId) {
        throw 'No verified FRED history capability exists for this instrument.'
    }
    $capabilities = New-ProviderCapabilities -Source $source `
        -SupportedInstrumentIds @($Instrument.instrumentId) `
        -Intervals @('1d') -HistoryDepth 'FRED series observations; coverage comes from the series metadata.'

    $culture = [System.Globalization.CultureInfo]::InvariantCulture
    $startDate = $Request.startUtc.ToUniversalTime().ToString('yyyy-MM-dd', $culture)
    $endDate = $Request.endUtc.ToUniversalTime().ToString('yyyy-MM-dd', $culture)
    $query = "series_id=$([uri]::EscapeDataString($seriesId))&observation_start=$startDate&observation_end=$endDate&sort_order=asc"
    $response = Invoke-FredHistoryRequest -Path 'series/observations' -Query $query -ApiKey $ApiKey `
        -Transport $Transport -TimeoutSeconds $TimeoutSeconds -CancellationToken $CancellationToken
    if ($null -eq $response -or $null -eq $response.PSObject.Properties['observations']) {
        throw 'FRED returned an invalid observations response.'
    }

    $observations = [System.Collections.Generic.List[object]]::new()
    foreach ($row in @($response.observations)) {
        $date = [DateTime]::MinValue
        if (-not [DateTime]::TryParseExact([string]$row.date, 'yyyy-MM-dd', $culture,
                [System.Globalization.DateTimeStyles]::None, [ref]$date)) {
            throw 'FRED returned an invalid observation date.'
        }
        $value = [decimal]0
        # FRED marks holidays and missing values with '.'; leave them as gaps.
        if (-not [decimal]::TryParse([string]$row.value, [System.Globalization.NumberStyles]::Number, $culture, [ref]$value)) {
            continue
        }
        $observationParameters = @{
            InstrumentId = $Instrument.instrumentId
            SourceId = $source.sourceId
            ObservedAtUtc = [DateTimeOffset]::new($date, [TimeSpan]::Zero)
            RetrievedAtUtc = $RetrievedAtUtc
            Interval = '1d'
            Value = $value
            Unit = $Instrument.unit
            Freshness = 'delayed'
        }
        if ($Instrument.quoteCurrency) { $observationParameters.Currency = $Instrument.quoteCurrency }
        $observation = New-MarketObservation @observationParameters
        Add-Member -InputObject $observation -NotePropertyName timestampPrecision -NotePropertyValue 'date'
        $observations.Add($observation)
    }

    $ordered = @($observations | Sort-Object observedAtUtc)
    $resultParameters = @{
        Capabilities = $capabilities
        RequestedUse = 'display'
        RetrievedAtUtc = $RetrievedAtUtc
        SourceTimestampUtc = if ($ordered.Count -gt 0) { $ordered[-1].observedAtUtc } else { $null }
        Freshness = if ($ordered.Count -gt 0) { 'delayed' } else { 'unavailable' }
        Records = $ordered
        Warnings = @('FRED observations are date-only daily values published after the close; they are not live prices.')
    }
    if ($ordered.Count -eq 0) { $resultParameters.EmptyResultReason = 'no-data' }
    New-ProviderResult @resultParameters
}