package miner

import (
	"testing"

	"crypto-miner-agent/config"
	"crypto-miner-agent/stats"
)

func TestPoolResourcesOKBlocksHighMinFreeRAM(t *testing.T) {
	r := stats.NewReporter()
	free := r.FreeMemoryMB()
	if free == 0 {
		t.Skip("free memory unavailable on this platform")
	}
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		MiningMode:   "always",
		MinFreeRAM:   int(free + 1_000_000),
		MaxCPUUsage:  0,
		MaxMemoryPct: 0,
	}}
	p := NewPool(1, cfg, r, nil)
	if p.resourcesOK() {
		t.Fatal("MinFreeRAM above available free RAM should block mining")
	}
}

func TestPoolResourcesOKBlocksLowMaxMemoryPct(t *testing.T) {
	r := stats.NewReporter()
	total := r.TotalMemoryMB()
	if total == 0 {
		t.Skip("total memory unavailable on this platform")
	}
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		MiningMode:   "always",
		MaxMemoryPct: 1,
		MaxCPUUsage:  0,
		MinFreeRAM:   0,
	}}
	p := NewPool(1, cfg, r, nil)
	if p.resourcesOK() {
		t.Fatal("MaxMemoryPct=1 should block when system memory use exceeds 1%")
	}
}

func TestPoolResourcesOKAllowsHighMaxCPU(t *testing.T) {
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		MiningMode:  "always",
		MaxCPUUsage: 100,
		MinFreeRAM:  0,
	}}
	p := NewPool(1, cfg, stats.NewReporter(), nil)
	if !p.resourcesOK() {
		t.Fatal("MaxCPUUsage=100 should allow mining when CPU is at most 100%")
	}
}

func TestPoolMiningAllowedRequiresResourcesAndSchedule(t *testing.T) {
	r := stats.NewReporter()
	free := r.FreeMemoryMB()
	if free == 0 {
		t.Skip("free memory unavailable on this platform")
	}
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		MiningMode:   "always",
		MinFreeRAM:   int(free + 1_000_000),
		MaxCPUUsage:  0,
		MaxMemoryPct: 0,
	}}
	p := NewPool(1, cfg, r, nil)
	if p.miningAllowed() {
		t.Fatal("miningAllowed should deny when resource guard fails even in always mode")
	}
}
