package platform

import (
	"bufio"
	"os"
	"strings"

	"gitgud.io/mike/mpv-manager/pkg/log"
)

func detectLinuxDistro() (string, string) {
	if _, err := os.Stat("/etc/os-release"); err == nil {
		return parseOSRelease()
	}

	if _, err := os.Stat("/etc/redhat-release"); err == nil {
		return parseRedHatRelease()
	}

	if _, err := os.Stat("/etc/debian_version"); err == nil {
		return "debian", "debian"
	}

	log.Warn("Could not detect Linux distribution")
	return "", ""
}

func parseOSRelease() (string, string) {
	file, err := os.Open("/etc/os-release")
	if err != nil {
		log.Debug("Failed to open /etc/os-release: " + err.Error())
		return "", ""
	}
	defer file.Close()

	var id, idLike string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "ID=") {
			id = strings.Trim(strings.TrimPrefix(line, "ID="), `"`)
		} else if strings.HasPrefix(line, "ID_LIKE=") {
			idLike = strings.Trim(strings.TrimPrefix(line, "ID_LIKE="), `"`)
		}
	}

	if id == "" {
		return "", ""
	}

	family := GetDistroFamily(id, idLike)
	return id, family
}

func parseRedHatRelease() (string, string) {
	file, err := os.ReadFile("/etc/redhat-release")
	if err != nil {
		log.Debug("Failed to read /etc/redhat-release: " + err.Error())
		return "", ""
	}
	content := string(file)
	content = strings.ToLower(content)

	switch {
	case strings.Contains(content, "fedora"):
		return "fedora", "rhel"
	case strings.Contains(content, "centos"):
		return "centos", "rhel"
	case strings.Contains(content, "red hat"):
		return "rhel", "rhel"
	default:
		return "rhel", "rhel"
	}
}

func GetDistroFamily(id, idLike string) string {
	id = strings.ToLower(id)
	idLike = strings.ToLower(idLike)

	debianFamily := []string{"debian", "ubuntu", "linuxmint", "mint", "pop", "elementaryos"}
	rhelFamily := []string{"rhel", "fedora", "centos", "redhat", "rocky", "almalinux"}
	archFamily := []string{"arch", "manjaro", "endeavouros", "garuda", "cachyos"}
	suseFamily := []string{"opensuse", "suse"}

	for _, d := range debianFamily {
		if id == d || strings.Contains(idLike, d) {
			return "debian"
		}
	}

	for _, d := range rhelFamily {
		if id == d || strings.Contains(idLike, d) {
			return "rhel"
		}
	}

	for _, d := range archFamily {
		if id == d || strings.Contains(idLike, d) {
			return "arch"
		}
	}

	for _, d := range suseFamily {
		if id == d || strings.Contains(idLike, d) {
			return "suse"
		}
	}

	return id
}
