package metric

import (
	"context"
	"strconv"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/tidbcloud/pkgv2/log"
	"github.com/tidbcloud/pkgv2/tracing"
	"github.com/tidbcloud/serverless-service/internal/domain/constant"
	"github.com/tidbcloud/serverless-service/internal/domain/repo"
	"go.opentelemetry.io/otel"
	"go.uber.org/zap"
)

const (
	RequestUnknown = "unknown"
	RequestSuccess = "200"

	maxWaitBranchReadyTime = 10 * time.Minute
)

var Tracer = otel.Tracer("branch-metric-collector")

var (
	BranchRequestedCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "requested_total",
			Help:      "Total number of branch requested.",
		},
		[]string{"type", "method", "code"},
	)

	BranchRequestedHistogram = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "request_handling_seconds",
			Help:      "Histogram of response latency (seconds) of request handled by branch.",
			Buckets:   prometheus.DefBuckets,
		},
		[]string{"type", "method", "code"},
	)

	BranchInternalErrCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "internal_err_total",
			Help:      "Total number of branch internal error.",
		},
		[]string{"method", "code"},
	)

	BranchReconcileErrCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "reconcile_err_total",
			Help:      "Total number of branch reconcile error.",
		},
		[]string{"method", "resource_id"},
	)

	BranchNumberGauge = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "number",
			Help:      "Total number of branch.",
		},
		[]string{"status"},
	)

	BranchLimitJobProcessCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: MetricNamespace,
			Name:      "branch_limit_process_statistics_total",
			Help:      "Counter for branch storage limit job statistics",
		},
		[]string{"provider", "region", "kubernetes", "status", "reason"},
	)

	BranchSyncHandlerCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: MetricNamespace,
			Subsystem: "branch",
			Name:      "sync_process_statistics_total",
			Help:      "Counter for branch sync handler statistics",
		},
		[]string{"event_id", "cluster_id", "event_type", "status"},
	)

	BranchWaitReadyTime = prometheus.NewDesc(
		prometheus.BuildFQName(MetricNamespace, "branch", "wait_ready_duration_seconds"),
		"Duration in seconds to wait for branch ready",
		[]string{"branch_id", "name", "tenant_id", "project_id", "main_branch_id"},
		nil)
)

func init() {
	prometheus.MustRegister(BranchRequestedCounter)
	prometheus.MustRegister(BranchRequestedHistogram)
	prometheus.MustRegister(BranchInternalErrCounter)
	prometheus.MustRegister(BranchReconcileErrCounter)
	prometheus.MustRegister(BranchNumberGauge)
	prometheus.MustRegister(BranchLimitJobProcessCounter)
	prometheus.MustRegister(BranchSyncHandlerCounter)
}

type BranchCreateTimeCollector struct {
	branchRepo repo.BranchRepo
}

func NewBranchCreateTimeCollector(branchRepo repo.BranchRepo) *BranchCreateTimeCollector {
	return &BranchCreateTimeCollector{
		branchRepo: branchRepo,
	}
}

func (c *BranchCreateTimeCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- BranchWaitReadyTime
}

func (c *BranchCreateTimeCollector) Collect(ch chan<- prometheus.Metric) {
	ctx := context.Background()
	var err error
	ctx, span := Tracer.Start(ctx, "MetricsCollector.Collect")
	log.Info(ctx, "start to collect branch create time")
	defer func() {
		tracing.EndSpan(span, err)
	}()

	brs, err := c.branchRepo.ListBranchesByStatuses(ctx, constant.BranchStatusPending, constant.BranchStatusCreating)
	if err != nil {
		return
	}

	for _, br := range brs {
		duration := time.Since(br.CreatedAt)
		if duration > maxWaitBranchReadyTime {
			ch <- prometheus.MustNewConstMetric(
				BranchWaitReadyTime,
				prometheus.GaugeValue,
				duration.Seconds(),
				br.ID,
				br.Name,
				strconv.FormatUint(br.TenantID, 10),
				strconv.FormatUint(br.ProjectID, 10),
				br.MainBranchID,
			)

			log.Error(ctx, "branch wait ready timeout", zap.String("branchID", br.ID))
		}
	}
}
