package metrics

import (
	"strconv"
	"time"

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

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

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

type fstreeMetrics struct {
	mode        *shardIDPathModeValue
	reqDuration *prometheus.HistogramVec
	put         *prometheus.CounterVec
	get         *prometheus.CounterVec
}

func newFSTreeMetrics() *fstreeMetrics {
	return &fstreeMetrics{
		mode: newShardIDPathMode(fstreeSubSystem, "mode", "FSTree mode value"),
		reqDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: fstreeSubSystem,
			Name:      "request_duration_seconds",
			Help:      "Accumulated FSTree request process duration",
		}, []string{shardIDLabel, successLabel, pathLabel, methodLabel}),
		put: metrics.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: fstreeSubSystem,
			Name:      "put_bytes",
			Help:      "Accumulated payload size written to FSTree",
		}, []string{shardIDLabel, pathLabel}),
		get: metrics.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: fstreeSubSystem,
			Name:      "get_bytes",
			Help:      "Accumulated payload size read from FSTree",
		}, []string{shardIDLabel, pathLabel}),
	}
}

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

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

func (m *fstreeMetrics) MethodDuration(shardID, path string, method string, d time.Duration, success bool) {
	m.reqDuration.With(prometheus.Labels{
		shardIDLabel: shardID,
		pathLabel:    path,
		successLabel: strconv.FormatBool(success),
		methodLabel:  method,
	}).Observe(d.Seconds())
}

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

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