package metrics

import (
	"strconv"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/shard/mode"
	"git.frostfs.info/TrueCloudLab/frostfs-observability/metrics"
	"github.com/prometheus/client_golang/prometheus"
)

type PiloramaMetrics interface {
	SetMode(shardID string, m mode.Mode)
	Close(shardID string)

	AddMethodDuration(shardID string, method string, d time.Duration, success bool)
}

func newPiloramaMetrics() *piloramaMetrics {
	return &piloramaMetrics{
		mode: newShardIDMode(piloramaSubSystem, "mode", "Pilorama mode"),
		reqDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: piloramaSubSystem,
			Name:      "request_duration_seconds",
			Help:      "Accumulated Pilorama request process duration",
		}, []string{shardIDLabel, successLabel, methodLabel}),
	}
}

type piloramaMetrics struct {
	mode        *shardIDModeValue
	reqDuration *prometheus.HistogramVec
}

func (m *piloramaMetrics) SetMode(shardID string, mode mode.Mode) {
	m.mode.SetMode(shardID, mode.String())
}

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

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