package core

import (
	"sync/atomic"
	"time"
)

// Metrics Core 监控指标
type Metrics struct {
	// 连接统计
	activeConnections atomic.Int64
	totalConnections  atomic.Int64

	// 流量统计
	bytesSent     atomic.Uint64
	bytesReceived atomic.Uint64

	// 策略统计
	strategyFallbacks atomic.Int64
	lastSwitchTime    atomic.Int64 // Unix timestamp
}

// NewMetrics 创建监控指标
func NewMetrics() *Metrics {
	return &Metrics{}
}

// GetActiveConnections 获取活跃连接数
func (m *Metrics) GetActiveConnections() int64 {
	return m.activeConnections.Load()
}

// IncrActiveConnections 增加活跃连接数
func (m *Metrics) IncrActiveConnections() {
	m.activeConnections.Add(1)
	m.totalConnections.Add(1)
}

// DecrActiveConnections 减少活跃连接数
func (m *Metrics) DecrActiveConnections() {
	m.activeConnections.Add(-1)
}

// AddBytesSent 增加发送字节数
func (m *Metrics) AddBytesSent(n uint64) {
	m.bytesSent.Add(n)
}

// AddBytesReceived 增加接收字节数
func (m *Metrics) AddBytesReceived(n uint64) {
	m.bytesReceived.Add(n)
}

// IncrStrategyFallbacks 增加策略降级次数
func (m *Metrics) IncrStrategyFallbacks() {
	m.strategyFallbacks.Add(1)
	m.lastSwitchTime.Store(time.Now().Unix())
}

// GetTotalConnections 获取总连接数
func (m *Metrics) GetTotalConnections() int64 {
	return m.totalConnections.Load()
}

// GetBytesSent 获取发送字节数
func (m *Metrics) GetBytesSent() uint64 {
	return m.bytesSent.Load()
}

// GetBytesReceived 获取接收字节数
func (m *Metrics) GetBytesReceived() uint64 {
	return m.bytesReceived.Load()
}

// GetStrategyFallbacks 获取策略降级次数
func (m *Metrics) GetStrategyFallbacks() int64 {
	return m.strategyFallbacks.Load()
}

// GetLastSwitchTime 获取最后切换时间
func (m *Metrics) GetLastSwitchTime() time.Time {
	return time.Unix(m.lastSwitchTime.Load(), 0)
}
