package monitoring

import (
	"context"
	"database/sql"
	"log"
	"runtime"
	"time"

	"gorm.io/gorm"
)

// StartSystemMetricsCollector 启动后台系统指标采集循环
// 每 15 秒采集一次：Go runtime 指标 + 数据库连接池状态
// CRIT-03: 这是 SLO 错误预算追踪的基础数据来源
func StartSystemMetricsCollector(ctx context.Context, m *Metrics, slo *SLOMetrics, db *gorm.DB) {
	ticker := time.NewTicker(15 * time.Second)
	defer ticker.Stop()

	log.Println("[monitoring] system metrics collector started (interval=15s)")

	for {
		select {
		case <-ctx.Done():
			log.Println("[monitoring] system metrics collector stopped")
			return
		case <-ticker.C:
			collectRuntimeMetrics(m)
			collectDBMetrics(slo, db)
		}
	}
}

// collectRuntimeMetrics 采集 Go runtime 指标
func collectRuntimeMetrics(m *Metrics) {
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)

	m.SetMemoryUsage(float64(memStats.Alloc))
	m.SetGoroutines(float64(runtime.NumGoroutine()))
}

// collectDBMetrics 采集数据库连接池指标并上报 SLO 指标
func collectDBMetrics(slo *SLOMetrics, db *gorm.DB) {
	if db == nil {
		return
	}

	sqlDB, err := db.DB()
	if err != nil {
		return
	}

	updateDBConnectionMetricsFromStats(slo, sqlDB.Stats())
}

// updateDBConnectionMetricsFromStats 从 sql.DBStats 更新连接池指标
func updateDBConnectionMetricsFromStats(slo *SLOMetrics, stats sql.DBStats) {
	if slo == nil {
		return
	}
	slo.SetDBConnections(
		float64(stats.InUse),
		float64(stats.MaxOpenConnections),
	)
}
