//go:build darwin && !cgo

package platform

import (
	"fmt"
	"runtime"
	"strings"

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

func detectCodecSupportDarwin() ([]string, error) {
	if runtime.GOOS != "darwin" {
		return nil, fmt.Errorf("not running on macOS")
	}

	log.Info("Using model-based codec detection")
	return detectCodecSupportByModel()
}

func detectCodecSupportByModel() ([]string, error) {
	info := detectGPUDarwin()

	if len(info.Models) == 0 {
		return []string{"av1", "hevc", "avc"}, nil
	}

	cpuModel := strings.ToLower(info.Models[0])

	return getCodecsForModel(cpuModel)
}

func getCodecsForModel(cpuModel string) ([]string, error) {
	modelNum := extractModelNumber(cpuModel)

	if strings.HasPrefix(modelNum, "m1") {
		return []string{"hevc", "avc", "prores"}, nil
	}

	if strings.HasPrefix(modelNum, "m2") {
		return []string{"hevc", "avc", "vp9", "av1", "prores"}, nil
	}

	if strings.HasPrefix(modelNum, "m3") {
		return []string{"hevc", "avc", "vp9", "av1", "prores"}, nil
	}

	if strings.HasPrefix(modelNum, "m4") {
		return []string{"hevc", "avc", "vp9", "av1", "prores"}, nil
	}

	return []string{"av1", "hevc", "avc"}, nil
}

func extractModelNumber(cpuModel string) string {
	cpuModel = strings.ToLower(cpuModel)

	if strings.Contains(cpuModel, "m1") {
		return "m1"
	}
	if strings.Contains(cpuModel, "m2") {
		return "m2"
	}
	if strings.Contains(cpuModel, "m3") {
		return "m3"
	}
	if strings.Contains(cpuModel, "m4") {
		return "m4"
	}
	if strings.Contains(cpuModel, "m5") {
		return "m5"
	}

	return ""
}
