package viral

import (
	"strings"
)

const (
	DefaultSelectedTagCount = 5
	MaxScanTags             = 6
)

type SuggestedTag struct {
	Tag          string `json:"tag"`
	Reason       string `json:"reason,omitempty"`
	SearchIntent string `json:"searchIntent,omitempty"`
	SearchType   string `json:"searchType,omitempty"`
}

// PickDefaultSelectedTags chooses a lean set for scanning (saves search API quota).
func PickDefaultSelectedTags(tags []SuggestedTag) []string {
	short := []string{}
	scenario := []string{}
	quote := []string{}
	account := []string{}

	for _, item := range tags {
		tag := strings.TrimSpace(item.Tag)
		if tag == "" {
			continue
		}
		st := strings.TrimSpace(item.SearchType)
		if strings.HasPrefix(tag, "@") || st == "帳號" {
			account = append(account, tag)
			continue
		}
		switch st {
		case "短詞":
			short = append(short, tag)
		case "情境":
			scenario = append(scenario, tag)
		case "語錄":
			quote = append(quote, tag)
		default:
			if len([]rune(tag)) <= 4 {
				short = append(short, tag)
			} else {
				scenario = append(scenario, tag)
			}
		}
	}

	out := []string{}
	seen := map[string]struct{}{}
	add := func(tag string) {
		tag = strings.TrimSpace(tag)
		if tag == "" {
			return
		}
		if _, ok := seen[tag]; ok {
			return
		}
		seen[tag] = struct{}{}
		out = append(out, tag)
	}
	for _, tag := range short {
		if len(out) >= 2 {
			break
		}
		add(tag)
	}
	for _, tag := range scenario {
		if len(out) >= 4 {
			break
		}
		add(tag)
	}
	for _, tag := range quote {
		if len(out) >= 5 {
			break
		}
		add(tag)
	}
	for _, tag := range account {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	for _, tag := range short {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	for _, tag := range scenario {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	if len(out) > MaxScanTags {
		out = out[:MaxScanTags]
	}
	return out
}

func TagStrings(tags []SuggestedTag) []string {
	out := make([]string, 0, len(tags))
	for _, item := range tags {
		if tag := strings.TrimSpace(item.Tag); tag != "" {
			out = append(out, tag)
		}
	}
	return out
}
