package utils

import (
	"fmt"
	"strings"
)

// 工具函数常量
const (
	SizeUnit  = 1024
	SizeUnits = "KMGTPE" // 文件大小单位：KB, MB, GB, TB, PB, EB
)

// FilterEmptyStrings 过滤掉路径中的空字符串。
func FilterEmptyStrings(parts []string) []string {
	var result []string
	for _, part := range parts {
		if part != "" {
			result = append(result, part)
		}
	}
	return result
}

// FormatSize 格式化文件大小为人类可读的字符串。
func FormatSize(bytes int64) string {
	if bytes < SizeUnit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := int64(SizeUnit), 0
	for n := bytes / SizeUnit; n >= SizeUnit; n /= SizeUnit {
		div *= SizeUnit
		exp++
	}
	if exp >= len(SizeUnits) {
		exp = len(SizeUnits) - 1
	}
	return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), SizeUnits[exp])
}

// FormatWebAddress 将 host:port 格式转换为可直接访问的 URL
func FormatWebAddress(address string) string {
	addr := strings.TrimSpace(address)
	if addr == "" {
		addr = "127.0.0.1:8888"
	}

	formatted := addr
	if strings.HasPrefix(addr, ":") {
		formatted = "127.0.0.1" + addr
	} else if strings.HasPrefix(addr, "0.0.0.0") {
		formatted = strings.Replace(addr, "0.0.0.0", "127.0.0.1", 1)
	}

	if !strings.HasPrefix(formatted, "http://") && !strings.HasPrefix(formatted, "https://") {
		formatted = "http://" + formatted
	}

	return formatted
}
