package utils

import (
	"strconv"
	"strings"
)

// ParseMemoryToMB parses a memory string and returns the value in MB
// Supports: Gi, Mi, Ki, G, M, K (case-insensitive) or plain numbers (assumed MB)
func ParseMemoryToMB(memory string) int {
	if len(memory) == 0 {
		return 4096 // Default: 4GB
	}

	// Remove whitespace and convert to lowercase for case-insensitive parsing
	memory = strings.TrimSpace(strings.ToLower(memory))

	// Check for unit suffix (case-insensitive)
	if strings.HasSuffix(memory, "gi") || strings.HasSuffix(memory, "g") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(memory, "gi"), "g"), 64)
		if err == nil {
			return int(value * 1024) // Convert GiB to MB
		}
	} else if strings.HasSuffix(memory, "mi") || strings.HasSuffix(memory, "m") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(memory, "mi"), "m"), 64)
		if err == nil {
			return int(value) // Already in MB
		}
	} else if strings.HasSuffix(memory, "ki") || strings.HasSuffix(memory, "k") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(memory, "ki"), "k"), 64)
		if err == nil {
			return int(value / 1024) // Convert KiB to MB
		}
	}

	// Try parsing as number (assume MB)
	value, err := strconv.Atoi(memory)
	if err == nil {
		return value
	}

	return 4096 // Default if parsing fails
}

// ParseMemoryToGB parses a memory string and returns the value in GB
// Supports: Gi, Mi, Ki, G, M, K (case-insensitive) or plain numbers (assumed GB)
func ParseMemoryToGB(memory string) int {
	memoryMB := ParseMemoryToMB(memory)
	return memoryMB / 1024 // Convert MB to GB
}

// ParseDiskToGB parses a disk string and returns the value in GB
// Supports: Ti, Gi, Mi, T, G, M (case-insensitive) or plain numbers (assumed GB)
func ParseDiskToGB(disk string) int {
	if len(disk) == 0 {
		return 50 // Default: 50GB
	}

	// Remove whitespace and convert to lowercase for case-insensitive parsing
	disk = strings.TrimSpace(strings.ToLower(disk))

	// Check for unit suffix (case-insensitive)
	if strings.HasSuffix(disk, "ti") || strings.HasSuffix(disk, "t") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(disk, "ti"), "t"), 64)
		if err == nil {
			return int(value * 1024) // Convert TiB to GB
		}
	} else if strings.HasSuffix(disk, "gi") || strings.HasSuffix(disk, "g") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(disk, "gi"), "g"), 64)
		if err == nil {
			return int(value) // Already in GB
		}
	} else if strings.HasSuffix(disk, "mi") || strings.HasSuffix(disk, "m") {
		value, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSuffix(disk, "mi"), "m"), 64)
		if err == nil {
			return int(value / 1024) // Convert MiB to GB
		}
	}

	// Try parsing as number (assume GB)
	value, err := strconv.Atoi(disk)
	if err == nil {
		return value
	}

	return 50 // Default if parsing fails
}

