package metrics

import (
	"strconv"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-observability/metrics"
	"github.com/prometheus/client_golang/prometheus"
)

type BlobstoreMetrics interface {
	SetMode(shardID string, readOnly bool)
	Close(shardID string)

	MethodDuration(shardID string, method string, d time.Duration, success bool, withStorageID NullBool)
	AddPut(shardID string, size int)
	AddGet(shardID string, size int)
}

type blobstoreMetrics struct {
	mode        *shardIDModeValue
	reqDuration *prometheus.HistogramVec
	put         *prometheus.CounterVec
	get         *prometheus.CounterVec
}

func newBlobstoreMetrics() *blobstoreMetrics {
	return &blobstoreMetrics{
		mode: newShardIDMode(blobstoreSubSystem, "mode", "Blobstore mode value"),
		reqDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: blobstoreSubSystem,
			Name:      "request_duration_seconds",
			Help:      "Accumulated Blobstore request process duration",
		}, []string{shardIDLabel, successLabel, methodLabel, withStorageIDLabel}),
		put: metrics.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: blobstoreSubSystem,
			Name:      "put_bytes",
			Help:      "Accumulated payload size written to Blobstore",
		}, []string{shardIDLabel}),
		get: metrics.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: blobstoreSubSystem,
			Name:      "get_bytes",
			Help:      "Accumulated payload size read from Blobstore",
		}, []string{shardIDLabel}),
	}
}

func (m *blobstoreMetrics) SetMode(shardID string, readOnly bool) {
	m.mode.SetMode(shardID, modeFromBool(readOnly))
}

func (m *blobstoreMetrics) Close(shardID string) {
	m.mode.SetMode(shardID, closedMode)
	m.reqDuration.DeletePartialMatch(prometheus.Labels{
		shardIDLabel: shardID,
	})
	m.get.DeletePartialMatch(prometheus.Labels{
		shardIDLabel: shardID,
	})
	m.put.DeletePartialMatch(prometheus.Labels{
		shardIDLabel: shardID,
	})
}

func (m *blobstoreMetrics) MethodDuration(shardID string, method string, d time.Duration, success bool, withStorageID NullBool) {
	m.reqDuration.With(prometheus.Labels{
		shardIDLabel:       shardID,
		successLabel:       strconv.FormatBool(success),
		methodLabel:        method,
		withStorageIDLabel: withStorageID.String(),
	}).Observe(d.Seconds())
}

func (m *blobstoreMetrics) AddPut(shardID string, size int) {
	m.put.With(prometheus.Labels{
		shardIDLabel: shardID,
	}).Add(float64(size))
}

func (m *blobstoreMetrics) AddGet(shardID string, size int) {
	m.get.With(prometheus.Labels{
		shardIDLabel: shardID,
	}).Add(float64(size))
}