using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using StellaOps.Scanner.Worker.Processing;

namespace StellaOps.Scanner.Worker.Diagnostics;

public sealed class ScannerWorkerMetrics
{
    private readonly Histogram<double> _queueLatencyMs;
    private readonly Histogram<double> _jobDurationMs;
    private readonly Histogram<double> _stageDurationMs;
    private readonly Counter<long> _jobsCompleted;
    private readonly Counter<long> _jobsFailed;

    public ScannerWorkerMetrics()
    {
        _queueLatencyMs = ScannerWorkerInstrumentation.Meter.CreateHistogram<double>(
            "scanner_worker_queue_latency_ms",
            unit: "ms",
            description: "Time from job enqueue to lease acquisition.");
        _jobDurationMs = ScannerWorkerInstrumentation.Meter.CreateHistogram<double>(
            "scanner_worker_job_duration_ms",
            unit: "ms",
            description: "Total processing duration per job.");
        _stageDurationMs = ScannerWorkerInstrumentation.Meter.CreateHistogram<double>(
            "scanner_worker_stage_duration_ms",
            unit: "ms",
            description: "Stage execution duration per job.");
        _jobsCompleted = ScannerWorkerInstrumentation.Meter.CreateCounter<long>(
            "scanner_worker_jobs_completed_total",
            description: "Number of successfully completed scan jobs.");
        _jobsFailed = ScannerWorkerInstrumentation.Meter.CreateCounter<long>(
            "scanner_worker_jobs_failed_total",
            description: "Number of scan jobs that failed permanently.");
    }

    public void RecordQueueLatency(ScanJobContext context, TimeSpan latency)
    {
        if (latency <= TimeSpan.Zero)
        {
            return;
        }

        _queueLatencyMs.Record(latency.TotalMilliseconds, CreateTags(context));
    }

    public void RecordJobDuration(ScanJobContext context, TimeSpan duration)
    {
        if (duration <= TimeSpan.Zero)
        {
            return;
        }

        _jobDurationMs.Record(duration.TotalMilliseconds, CreateTags(context));
    }

    public void RecordStageDuration(ScanJobContext context, string stage, TimeSpan duration)
    {
        if (duration <= TimeSpan.Zero)
        {
            return;
        }

        _stageDurationMs.Record(duration.TotalMilliseconds, CreateTags(context, stage: stage));
    }

    public void IncrementJobCompleted(ScanJobContext context)
    {
        _jobsCompleted.Add(1, CreateTags(context));
    }

    public void IncrementJobFailed(ScanJobContext context, string failureReason)
    {
        _jobsFailed.Add(1, CreateTags(context, failureReason: failureReason));
    }

    private static KeyValuePair<string, object?>[] CreateTags(ScanJobContext context, string? stage = null, string? failureReason = null)
    {
        var tags = new List<KeyValuePair<string, object?>>(stage is null ? 5 : 6)
        {
            new("job.id", context.JobId),
            new("scan.id", context.ScanId),
            new("attempt", context.Lease.Attempt),
        };

        if (context.Lease.Metadata.TryGetValue("queue", out var queueName) && !string.IsNullOrWhiteSpace(queueName))
        {
            tags.Add(new KeyValuePair<string, object?>("queue", queueName));
        }

        if (context.Lease.Metadata.TryGetValue("job.kind", out var jobKind) && !string.IsNullOrWhiteSpace(jobKind))
        {
            tags.Add(new KeyValuePair<string, object?>("job.kind", jobKind));
        }

        if (!string.IsNullOrWhiteSpace(stage))
        {
            tags.Add(new KeyValuePair<string, object?>("stage", stage));
        }

        if (!string.IsNullOrWhiteSpace(failureReason))
        {
            tags.Add(new KeyValuePair<string, object?>("reason", failureReason));
        }

        return tags.ToArray();
    }
}
