using KArtSell.BuildingBlocks.Observability;

namespace KArtSell.Modules.ModelOperations.Observability;

/// <summary>
/// Real observability service backed by actual database queries.
/// Maps MetricsSql results to IObservabilityService contract.
/// </summary>
public sealed class ObservabilityService(MetricsSql metricsSql) : IObservabilityService
{
    public async Task<ObservabilityMetricsDto> GetMetricsAsync(CancellationToken cancellationToken)
    {
        var batchSla = await metricsSql.GetBatchSlaAsync(cancellationToken);
        var dataQuality = await metricsSql.GetDataQualityQuarantineAsync(cancellationToken);
        var duplicateDetection = await metricsSql.GetDuplicateDetectionAsync(cancellationToken);
        var reconciliation = await metricsSql.GetReconciliationBreaksAsync(cancellationToken);
        var modelDrift = await metricsSql.GetModelDriftAsync(cancellationToken);

        return new ObservabilityMetricsDto
        {
            BatchSla = batchSla.HasValue
                ? new BatchSlaMetrics
                {
                    QueueDepth = 0,
                    AverageCompletionTimeSeconds = batchSla.Value.AvgTime.TotalSeconds,
                    RetryRate = batchSla.Value.Total > 0
                        ? (batchSla.Value.Total - batchSla.Value.OnTime) / (double)batchSla.Value.Total
                        : 0
                }
                : null,
            DataQuality = dataQuality.HasValue
                ? new DataQualityMetrics
                {
                    QuarantineCount = dataQuality.Value.Quarantined,
                    AgeMinutes = 0,
                    TopFailureReasons = dataQuality.Value.Errors
                }
                : null,
            DuplicateDetection = duplicateDetection.HasValue
                ? new DuplicateDetectionMetrics
                {
                    ConstraintViolationCount = duplicateDetection.Value.Detected,
                    LastDetected = duplicateDetection.Value.LastCheck
                }
                : null,
            Reconciliation = reconciliation.HasValue
                ? new ReconciliationMetrics
                {
                    CompletenessPercentage = 100,
                    AuditRecordsCount = reconciliation.Value.Detected
                }
                : null,
            ModelDrift = modelDrift.HasValue
                ? new ModelDriftMetrics
                {
                    OosPerformanceValue = (double)modelDrift.Value.Current,
                    BaselineComparison = (double)modelDrift.Value.Baseline,
                    DegradationFlag = modelDrift.Value.Current < modelDrift.Value.Baseline
                }
                : null
        };
    }
}
