package service

import (
	"os"
	"path/filepath"
	"sort"
	"strings"
)

var subscribeTemplateFiles = map[string]string{
	"singbox":   filepath.Join("submodule", "singbox.json"),
	"clash":     filepath.Join("submodule", "clash.yaml"),
	"clashmeta": filepath.Join("submodule", "clash-meta.yaml"),
	"stash":     filepath.Join("submodule", "stash.yaml"),
	"surge":     filepath.Join("submodule", "surge.toml"),
	"surfboard": filepath.Join("submodule", "surfboard.toml"),
}

func SubscribeTemplateSettingKey(name string) string {
	return "subscribe_template_" + strings.TrimSpace(strings.ToLower(name))
}

func DefaultSubscribeTemplate(name string) string {
	path, ok := subscribeTemplateFiles[strings.TrimSpace(strings.ToLower(name))]
	if !ok {
		return ""
	}

	content, err := os.ReadFile(path)
	if err != nil {
		return ""
	}
	return string(content)
}

func GetSubscribeTemplate(name string) string {
	key := SubscribeTemplateSettingKey(name)
	if value, ok := GetSetting(key); ok && strings.TrimSpace(value) != "" {
		return value
	}
	return DefaultSubscribeTemplate(name)
}

func GetAllSubscribeTemplates() map[string]string {
	keys := make([]string, 0, len(subscribeTemplateFiles))
	for key := range subscribeTemplateFiles {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	result := make(map[string]string, len(keys))
	for _, key := range keys {
		result[SubscribeTemplateSettingKey(key)] = GetSubscribeTemplate(key)
	}
	return result
}
