import type { BrandData, BrandProductData } from '../types/brand'
import {
  formatProductContextForPrompt,
  hasProductContext,
  parseProductContext,
  serializeProductContext,
} from './productContext'
import { scoreProductForTag } from './productMatch'

export type CatalogProduct = {
  id: string
  label: string
  context: string
  matchTags: string[]
}

export type CatalogBrand = {
  id: string
  name: string
  products: CatalogProduct[]
}

/** 品牌庫列表皆為目錄品牌（找 TA 主題另存 placement_topics）。 */
export function isCatalogBrand(_item: BrandData): boolean {
  return true
}

export function toCatalogBrand(brand: BrandData): CatalogBrand {
  return {
    id: brand.id,
    name: brand.display_name?.trim() || '未命名品牌',
    products: (brand.products ?? []).map((item) => ({
      id: item.id,
      label: item.label,
      context: item.product_context,
      matchTags: item.match_tags ?? [],
    })),
  }
}

export function brandHasCatalogProducts(brand: BrandData | null | undefined): boolean {
  if (!brand) return false
  if ((brand.products?.length ?? 0) > 0) {
    return brand.products!.some((item) => hasProductContext(item.product_context))
  }
  return hasProductContext(brand.product_context) || !!brand.product_brief?.trim()
}

export function buildMergedProductContext(
  brandName: string,
  productContext: string,
  productLabel: string,
): string {
  const fields = parseProductContext(productContext)
  return serializeProductContext({
    ...fields,
    brand: brandName.trim() || fields.brand,
    product: fields.product?.trim() || productLabel.trim(),
  })
}

export function recommendProductFromCatalog(
  products: CatalogProduct[],
  options: {
    searchTag?: string | null
    defaultProductId?: string | null
  },
): CatalogProduct | null {
  if (products.length === 0) return null

  const defaultProduct = options.defaultProductId
    ? products.find((p) => p.id === options.defaultProductId) ?? null
    : null

  if (!options.searchTag?.trim()) {
    return defaultProduct ?? products[0]
  }

  const scored = products
    .map((product) => ({
      product,
      score: scoreProductForTag(options.searchTag, product.matchTags),
    }))
    .sort((a, b) => b.score - a.score)

  const best = scored[0]
  if (best && best.score > 0) return best.product
  return defaultProduct ?? products[0]
}

export function formatCatalogProductSummary(
  brandName: string,
  productContext: string,
  productLabel: string,
): string {
  const merged = buildMergedProductContext(brandName, productContext, productLabel)
  return formatProductContextForPrompt(merged) || merged
}

export function summarizeCatalogProduct(product: BrandProductData, brandName: string): string {
  return (
    formatCatalogProductSummary(brandName, product.product_context, product.label) ||
    product.label
  )
}