package utils

import (
	"math"
	"strconv"

	"github.com/AFASystems/presence/internal/pkg/model"
)

// CalculateDistance calculates the approximate distance from RSSI and TX power
// Uses a hybrid approach combining logarithmic and polynomial models
func CalculateDistance(adv model.BeaconAdvertisement) float64 {
	txPower := twosComp(adv.TXPower)
	ratio := float64(adv.RSSI) / float64(txPower)

	if ratio < 1.0 {
		return math.Pow(ratio, 10)
	} else {
		return (0.89976)*math.Pow(ratio, 7.7095) + 0.111
	}
}

// TwosComp converts a two's complement hexadecimal string to int64
func twosComp(inp string) int64 {
	i, err := strconv.ParseInt("0x"+inp, 0, 64)
	if err != nil {
		return 0
	}

	if i >= 128 {
		return i - 256
	}
	return i
}

// ValidateRSSI validates if RSSI value is within reasonable bounds
func ValidateRSSI(rssi int64) bool {
	return rssi >= -120 && rssi <= 0
}

// ValidateTXPower validates if TX power is within reasonable bounds
func ValidateTXPower(txPower string) bool {
	power := twosComp(txPower)
	return power >= -128 && power <= 127
}
