/**
 * Investigation script: enumerate distinct Brand.industry and location values,
 * show the canonicalization result for each, and sample AiAttribution fragments.
 *
 * Run from repo root (needs DATABASE_URL in env):
 *   npx ts-node --compiler-options '{"module":"CommonJS"}' scripts/investigate-brand-cells.ts
 */

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  // 1. Distinct industry values
  const industryRows = await prisma.$queryRaw<{ industry: string | null; cnt: bigint }[]>`
    SELECT industry, COUNT(*)::bigint AS cnt
    FROM "Brand"
    GROUP BY industry
    ORDER BY cnt DESC
  `;
  console.log("\n=== Brand.industry distinct values ===");
  for (const r of industryRows) {
    console.log(`  ${JSON.stringify(r.industry)}  (n=${r.cnt})`);
  }

  // 2. Distinct legacy location values (non-null, non-empty)
  const locationRows = await prisma.$queryRaw<{ location: string; cnt: bigint }[]>`
    SELECT location, COUNT(*)::bigint AS cnt
    FROM "Brand"
    WHERE location IS NOT NULL AND location <> ''
    GROUP BY location
    ORDER BY cnt DESC
  `;
  console.log("\n=== Brand.location distinct values ===");
  for (const r of locationRows) {
    console.log(`  ${JSON.stringify(r.location)}  (n=${r.cnt})`);
  }

  // 3. All locations[] array elements flattened
  const locationsRows = await prisma.$queryRaw<{ loc: string; cnt: bigint }[]>`
    SELECT loc, COUNT(*)::bigint AS cnt
    FROM "Brand", unnest(locations) AS loc
    WHERE array_length(locations, 1) > 0
    GROUP BY loc
    ORDER BY cnt DESC
  `;
  console.log("\n=== Brand.locations[] distinct values (unnested) ===");
  for (const r of locationsRows) {
    console.log(`  ${JSON.stringify(r.loc)}  (n=${r.cnt})`);
  }

  // 4. Canonicalization coverage check
  // Dynamic import to run inside the same process
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const { canonicalizeVertical, canonicalizeMetro, getBrandCells } = await import(
    "../src/lib/market-position/cell"
  );

  console.log("\n=== Canonicalization: industry -> vertical ===");
  const industries = industryRows.map((r) => r.industry);
  for (const ind of industries) {
    console.log(`  ${JSON.stringify(ind)} -> "${canonicalizeVertical(ind)}"`);
  }

  console.log("\n=== Canonicalization: location -> metro ===");
  const allLocations = [
    ...locationRows.map((r) => r.location),
    ...locationsRows.map((r) => r.loc),
  ];
  const uniqueLocs = [...new Set(allLocations)];
  for (const loc of uniqueLocs) {
    console.log(`  ${JSON.stringify(loc)} -> "${canonicalizeMetro(loc)}"`);
  }

  // 5. Brand -> cell mapping (multi-vertical check)
  const brands = await prisma.brand.findMany({
    select: { id: true, name: true, industry: true, location: true, locations: true },
  });
  console.log("\n=== Brand -> cells (all brands) ===");
  for (const b of brands) {
    const cells = getBrandCells(b);
    console.log(`  [${b.name}] industry="${b.industry}" -> ${JSON.stringify(cells)}`);
  }

  // 6. Sample AiAttribution fragment shapes
  const attrs = await prisma.aiAttribution.findMany({
    select: { brandId: true, queryContext: true, landingPage: true, converted: true, dealValue: true, conversionType: true },
    orderBy: { id: "desc" },
    take: 20,
  });
  console.log("\n=== Sample AiAttribution rows (latest 20) ===");
  for (const a of attrs) {
    const qc = a.queryContext ? a.queryContext.slice(0, 120) : null;
    console.log(`  brandId=${a.brandId} converted=${a.converted} dealValue=${a.dealValue} convType=${a.conversionType}`);
    console.log(`    queryContext: ${JSON.stringify(qc)}`);
    console.log(`    landingPage:  ${JSON.stringify(a.landingPage)}`);
  }

  // 7. Distinct conversionType values in AiAttribution
  const ctRows = await prisma.$queryRaw<{ conversionType: string | null; cnt: bigint }[]>`
    SELECT "conversionType", COUNT(*)::bigint AS cnt
    FROM "AiAttribution"
    GROUP BY "conversionType"
    ORDER BY cnt DESC
  `;
  console.log("\n=== AiAttribution.conversionType distinct values ===");
  for (const r of ctRows) {
    console.log(`  ${JSON.stringify(r.conversionType)}  (n=${r.cnt})`);
  }

  await prisma.$disconnect();
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
