package social

import (
	"context"
	"time"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/metric/noop"
)

// meterName scopes the social domain's OpenTelemetry instruments.
const meterName = "scrabble/backend/social"

// socialMetrics holds the social domain's operational instruments. It defaults to
// no-ops (see defaultSocialMetrics); SetMetrics installs the real meter during
// startup wiring.
type socialMetrics struct {
	messages     metric.Int64Counter
	readDuration metric.Float64Histogram
}

// defaultSocialMetrics returns instruments backed by a no-op meter.
func defaultSocialMetrics() *socialMetrics {
	return newSocialMetrics(noop.NewMeterProvider().Meter(meterName))
}

// newSocialMetrics builds the instruments on meter, falling back to a no-op
// counter on the (rare) construction error.
func newSocialMetrics(meter metric.Meter) *socialMetrics {
	c, err := meter.Int64Counter("chat_messages_total",
		metric.WithDescription("Per-game chat entries posted, labelled by kind (message/nudge)."))
	if err != nil {
		c, _ = noop.NewMeterProvider().Meter(meterName).Int64Counter("chat_messages_total")
	}
	h, err := meter.Float64Histogram("chat_read_duration",
		metric.WithDescription("Time from a chat entry being posted to a recipient reading it, in seconds, labelled by kind (message/nudge)."),
		metric.WithUnit("s"))
	if err != nil {
		h, _ = noop.NewMeterProvider().Meter(meterName).Float64Histogram("chat_read_duration")
	}
	return &socialMetrics{messages: c, readDuration: h}
}

// SetMetrics installs the meter the social domain records to. It must be called
// during startup wiring; the default is a no-op meter.
func (svc *Service) SetMetrics(meter metric.Meter) {
	if meter == nil {
		return
	}
	svc.metrics = newSocialMetrics(meter)
	// chat_unread_messages observes the current backlog of unread chat entries at scrape
	// time (the partial index keeps the count cheap). A registration error is ignored —
	// the gauge is best-effort observability.
	_, _ = meter.Int64ObservableGauge("chat_unread_messages",
		metric.WithDescription("Chat entries with at least one recipient seat that has not read them yet."),
		metric.WithInt64Callback(func(ctx context.Context, o metric.Int64Observer) error {
			n, err := svc.store.countUnread(ctx)
			if err != nil {
				return err
			}
			o.Observe(n)
			return nil
		}))
}

// recordChat counts one posted chat entry of the given kind (message or nudge).
func (m *socialMetrics) recordChat(ctx context.Context, kind string) {
	m.messages.Add(ctx, 1, metric.WithAttributes(attribute.String("kind", kind)))
}

// recordRead records one chat entry's publish-to-read latency, labelled by kind. A
// non-positive duration (clock skew) is dropped.
func (m *socialMetrics) recordRead(ctx context.Context, kind string, d time.Duration) {
	if d <= 0 {
		return
	}
	m.readDuration.Record(ctx, d.Seconds(), metric.WithAttributes(attribute.String("kind", kind)))
}
