package stats

import (
	"runtime"
	"time"

	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/mem"
)

// Stats represents system statistics.
type Stats struct {
	CPUUsage  float64   `json:"cpu_usage"`
	RAMUsage  uint64    `json:"ram_usage"`
	RAMTotal  uint64    `json:"ram_total"`
	DiskUsage uint64    `json:"disk_usage"`
	DiskTotal uint64    `json:"disk_total"`
	Timestamp time.Time `json:"timestamp"`
	Hostname  string    `json:"hostname"`
}

// Collector gathers system statistics.
type Collector struct{}

// NewCollector creates a new stats collector.
func NewCollector() *Collector {
	return &Collector{}
}

// Collect gathers current system statistics.
func (c *Collector) Collect(hostname string) (*Stats, error) {
	cpuPercent, err := cpu.Percent(time.Second, false)
	if err != nil {
		return nil, err
	}

	memStats, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}

	diskStats, err := disk.Usage("/")
	if err != nil {
		return nil, err
	}

	var cpuUsage float64
	if len(cpuPercent) > 0 {
		cpuUsage = cpuPercent[0]
	}

	return &Stats{
		CPUUsage:  cpuUsage,
		RAMUsage:  memStats.Used,
		RAMTotal:  memStats.Total,
		DiskUsage: diskStats.Used,
		DiskTotal: diskStats.Total,
		Timestamp: time.Now(),
		Hostname:  hostname,
	}, nil
}

// GetNumCores returns the number of CPU cores.
func GetNumCores() int {
	return runtime.NumCPU()
}
