import {
  formatProductContextForPrompt,
  parseProductContext,
  serializeProductContext,
} from "@/lib/types/product-context";
import { scoreProductForTag } from "@/lib/types/product-match";

export interface CatalogProduct {
  id: string;
  label: string;
  context: string;
  matchTags: string[];
}

export interface CatalogBrand {
  id: string;
  name: string;
  notes: string | null;
  products: CatalogProduct[];
}

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);
}