package config

import (
	"runtime"

	"crypto-miner-agent/stats"
)

const randomXMBPerThread = 384

// AdaptToSystem tunes thread and memory limits for the host hardware.
func (c RuntimeConfig) AdaptToSystem(reporter *stats.Reporter) RuntimeConfig {
	if !c.AdaptToHardware {
	 return c
	}

	out := c
	totalMB := reporter.TotalMemoryMB()
	if totalMB == 0 {
		return out
	}

	if out.MinFreeRAM <= 0 || out.MinFreeRAM > int(totalMB/4) {
		minFree := int(totalMB / 10)
		if minFree < 512 {
			minFree = 512
		}
		out.MinFreeRAM = minFree
	}

	maxByRAM := int(float64(totalMB) * float64(out.MaxMemoryPct) / 100.0 / float64(randomXMBPerThread))
	if maxByRAM < 1 {
		maxByRAM = 1
	}

	threads := out.EffectiveThreads()
	if threads > maxByRAM {
		if out.ThreadMode == "fixed" {
			out.Threads = maxByRAM
		} else {
			cores := runtime.NumCPU()
			if cores < 1 {
				cores = 1
			}
			pct := int(float64(maxByRAM) / float64(cores) * 100.0)
			if pct < 10 {
				pct = 10
			}
			if pct > 100 {
				pct = 100
			}
			out.ThreadPercent = pct
		}
	}

	return out
}
