package placement

import (
	"strings"

	brandentity "haixun-backend/internal/model/brand/domain/entity"
)

func BuildMergedProductContext(brandName, productContext, productLabel string) string {
	fields := ParseProductContext(productContext)
	if name := strings.TrimSpace(brandName); name != "" {
		fields.Brand = name
	}
	if label := strings.TrimSpace(productLabel); label != "" && fields.Product == "" {
		fields.Product = label
	}
	return SerializeProductContext(fields)
}

func RecommendProduct(products []brandentity.Product, searchTag, defaultProductID string) *brandentity.Product {
	if len(products) == 0 {
		return nil
	}
	var defaultProduct *brandentity.Product
	if id := strings.TrimSpace(defaultProductID); id != "" {
		for i := range products {
			if products[i].ID == id {
				defaultProduct = &products[i]
				break
			}
		}
	}
	tag := strings.TrimSpace(searchTag)
	if tag == "" {
		if defaultProduct != nil {
			return defaultProduct
		}
		return &products[0]
	}

	bestScore := -1
	var best *brandentity.Product
	for i := range products {
		score := ScoreProductForTag(tag, products[i].MatchTags)
		if score > bestScore {
			bestScore = score
			best = &products[i]
		}
	}
	if best != nil && bestScore > 0 {
		return best
	}
	if defaultProduct != nil {
		return defaultProduct
	}
	return &products[0]
}

func ResolveBrandProductContext(brand brandentity.Brand, productID, searchTag string) string {
	if len(brand.Products) > 0 {
		picked := RecommendProduct(brand.Products, searchTag, productID)
		if picked != nil {
			return BuildMergedProductContext(brand.DisplayName, picked.ProductContext, picked.Label)
		}
	}
	if formatted := ProductBriefFromContext(brand.ProductContext); formatted != "" {
		return formatted
	}
	if brief := strings.TrimSpace(brand.ProductBrief); brief != "" {
		return brief
	}
	return ""
}

func FindProduct(brand brandentity.Brand, productID string) *brandentity.Product {
	id := strings.TrimSpace(productID)
	if id == "" {
		return nil
	}
	for i := range brand.Products {
		if brand.Products[i].ID == id {
			return &brand.Products[i]
		}
	}
	return nil
}
