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 of search queries. Prefer complete
// intent-preserving queries over short hashtags; short generic tags tend to
// drift away from niche copy-mission topics.
func PickDefaultSelectedTags(tags []SuggestedTag) []string {
	short := []string{}
	query := []string{}
	contextual := []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 "查詢", "情境":
			query = append(query, tag)
		case "短詞", "語錄":
			if len([]rune(tag)) >= 6 {
				query = append(query, tag)
			} else {
				short = append(short, tag)
			}
		default:
			if len([]rune(tag)) <= 4 {
				short = append(short, tag)
			} else {
				contextual = append(contextual, 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 query {
		if len(out) >= 4 {
			break
		}
		add(tag)
	}
	for _, tag := range contextual {
		if len(out) >= 4 {
			break
		}
		add(tag)
	}
	for _, tag := range account {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	for _, tag := range query {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	for _, tag := range contextual {
		if len(out) >= DefaultSelectedTagCount {
			break
		}
		add(tag)
	}
	for _, tag := range short {
		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
}
