package ana

import (
	"maps"
	"time"

	"gogs.inhome.blapointe.com/ana-ledger/src/ledger"
)

type Prediction []Predictor

func NewPrediction(predictor ...Predictor) Prediction {
	return Prediction(predictor)
}

func (prediction Prediction) Predict(register ledger.Register, window time.Duration) ledger.Register {
	return prediction.predict(register.Latest(), time.Now(), predictionTimes(window))
}

func (prediction Prediction) predict(latest ledger.Balances, from time.Time, these []time.Time) ledger.Register {
	latestT := from
	result := make(ledger.Register)
	for i := range these {
		k := these[i].Format("2006-01")
		result[k] = make(ledger.Balances)
		for k2, v2 := range latest {
			result[k][k2] = maps.Clone(v2)
		}

		elapsed := these[i].Sub(latestT)
		result[k] = prediction.predictOne(result[k], elapsed)

		latest = result[k]
		latestT = these[i]
	}
	return result
}

func (prediction Prediction) predictOne(balances ledger.Balances, elapsed time.Duration) ledger.Balances {
	for i := range prediction {
		next := prediction[i](balances, elapsed)
		balances = next
	}
	return balances
}
