package util

import (
	"os"
	"regexp"
	"strings"
	"time"
	"unicode"
)

var htmlTagRe = regexp.MustCompile(`<[^>]+>`)
var nonWordRe = regexp.MustCompile(`[^\w\s-]`)
var spaceOrUnderscoreRe = regexp.MustCompile(`[\s_]+`)
var multiDashRe = regexp.MustCompile(`-+`)

func FormatDescription(text string) string {
	if text == "" {
		return ""
	}
	text = htmlTagRe.ReplaceAllString(text, "")
	text = strings.ReplaceAll(text, "\r\n", "\n")
	text = strings.ReplaceAll(text, "\r", "\n")
	return strings.TrimSpace(text)
}

func Slugify(text string) string {
	text = strings.ToLower(strings.TrimSpace(text))
	text = nonWordRe.ReplaceAllString(text, "")
	text = spaceOrUnderscoreRe.ReplaceAllString(text, "-")
	text = multiDashRe.ReplaceAllString(text, "-")
	return strings.Trim(text, "-")
}

func LoadProxies(filepath string) []string {
	data, err := os.ReadFile(filepath)
	if err != nil {
		return []string{}
	}
	var proxies []string
	for _, line := range strings.Split(string(data), "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		if strings.HasPrefix(line, "http://") || strings.HasPrefix(line, "https://") {
			proxies = append(proxies, line)
		} else if strings.Contains(line, "@") {
			proxies = append(proxies, "http://"+line)
		} else {
			parts := strings.Split(line, ":")
			if len(parts) == 4 {
				proxies = append(proxies, "http://"+parts[2]+":"+parts[3]+"@"+parts[0]+":"+parts[1])
			} else {
				proxies = append(proxies, "http://"+line)
			}
		}
	}
	return proxies
}

func CurrentEpochMs() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}

func Ucwords(s string) string {
	words := strings.Fields(s)
	for i, w := range words {
		if w == "" {
			continue
		}
		r := []rune(w)
		r[0] = unicode.ToUpper(r[0])
		words[i] = string(r)
	}
	return strings.Join(words, " ")
}
