// ─── Query categorizer ────────────────────────────────────────────────────────

export type QueryCategory =
  | "branded"
  | "nonBrandedNational"
  | "nonBrandedLocal"
  | "longTailInformational";

export interface CategorizedQuery {
  query: string;
  category: QueryCategory;
}

export interface CategorizedQueries {
  branded: string[];
  nonBrandedNational: string[];
  nonBrandedLocal: string[];
  longTailInformational: string[];
}

const GEO_TERMS = /\bnear me\b|\bin\s+[a-z]|\b(city|town|county|state|region|local|nearby)\b|[a-z]+,\s*[a-z]{2}\b/i;
const INFO_PREFIXES = /^(how|what|why|when|where|should i|is it|can i|which|does|do)\b/i;
const MAX_PER_CATEGORY = 3;

export function categorizeQueries(
  brandName: string,
  queries: string[],
  brandLocation?: string,
): CategorizedQueries {
  const result: CategorizedQueries = {
    branded: [],
    nonBrandedNational: [],
    nonBrandedLocal: [],
    longTailInformational: [],
  };

  const brandLower = brandName.toLowerCase();
  const locationLower = brandLocation?.toLowerCase() ?? "";

  for (const q of queries) {
    const lower = q.toLowerCase().trim();
    if (!lower) continue;

    // Branded: contains brand name (case-insensitive)
    if (lower.includes(brandLower)) {
      if (result.branded.length < MAX_PER_CATEGORY) result.branded.push(q);
      continue;
    }

    // Informational: starts with question word
    if (INFO_PREFIXES.test(lower)) {
      if (result.longTailInformational.length < MAX_PER_CATEGORY) result.longTailInformational.push(q);
      continue;
    }

    // Local: geo terms or known location name in query
    const hasGeo = GEO_TERMS.test(lower) || (locationLower && lower.includes(locationLower));
    if (hasGeo) {
      if (result.nonBrandedLocal.length < MAX_PER_CATEGORY) result.nonBrandedLocal.push(q);
      continue;
    }

    // National: everything else
    if (result.nonBrandedNational.length < MAX_PER_CATEGORY) result.nonBrandedNational.push(q);
  }

  return result;
}

export function flattenCategorized(categorized: CategorizedQueries): CategorizedQuery[] {
  const out: CategorizedQuery[] = [];
  for (const q of categorized.branded) out.push({ query: q, category: "branded" });
  for (const q of categorized.nonBrandedNational) out.push({ query: q, category: "nonBrandedNational" });
  for (const q of categorized.nonBrandedLocal) out.push({ query: q, category: "nonBrandedLocal" });
  for (const q of categorized.longTailInformational) out.push({ query: q, category: "longTailInformational" });
  return out;
}
