/**
 * Auto-categorization script
 * Usage:
 *   npx tsx scripts/auto-categorize.ts          # categorize uncategorized only
 *   npx tsx scripts/auto-categorize.ts --all     # re-categorize everything
 *   npx tsx scripts/auto-categorize.ts --new     # only uncategorized (default)
 */

import pg from 'pg';
import {
  categorizeProduct,
  writeCategorizationResults,
  type ProductInput,
  type CategorizationResult,
} from '../src/lib/categories/auto-categorizer.js';

const { Pool } = pg;

async function main() {
  const args = process.argv.slice(2);
  const all = args.includes('--all');

  console.log(`🏷️  SneakerPicks Auto-Categorizer`);
  console.log(`   Mode: ${all ? 'ALL products' : 'Uncategorized only'}`);
  console.log('');

  const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
  });

  try {
    const whereClause = all
      ? 'WHERE 1=1'
      : 'WHERE categorized_at IS NULL OR categorization_version = 0';

    const { rows: products } = await pool.query<ProductInput>(
      `SELECT p.id, p.name, p.brand, p.gender, p.price, p.original_price
       FROM products p
       ${whereClause}
       AND NOT EXISTS (
         SELECT 1 FROM product_categories pc
         WHERE pc.product_id = p.id AND pc.source = 'manual'
       )
       ORDER BY p.created_at DESC`
    );

    console.log(`📦 Found ${products.length} products to categorize`);

    if (products.length === 0) {
      console.log('✅ Nothing to do!');
      return;
    }

    const results: CategorizationResult[] = [];
    let brandDetected = 0;
    let genderDetected = 0;
    let activityDetected = 0;

    for (const product of products) {
      const result = categorizeProduct(product);
      results.push(result);

      if (result.detectedBrand) brandDetected++;
      if (result.detectedGender) genderDetected++;
      if (result.detectedActivity) activityDetected++;
    }

    console.log('');
    console.log(`📊 Detection results:`);
    console.log(`   Brand:    ${brandDetected}/${products.length} (${((brandDetected / products.length) * 100).toFixed(1)}%)`);
    console.log(`   Gender:   ${genderDetected}/${products.length} (${((genderDetected / products.length) * 100).toFixed(1)}%)`);
    console.log(`   Activity: ${activityDetected}/${products.length} (${((activityDetected / products.length) * 100).toFixed(1)}%)`);
    console.log('');

    console.log('💾 Writing results to database...');
    const written = await writeCategorizationResults(results);
    console.log(`✅ Done! Wrote ${written} category assignments for ${products.length} products`);

    // Summary of categories assigned
    const categoryCounts = new Map<string, number>();
    for (const result of results) {
      for (const cat of result.categories) {
        categoryCounts.set(cat.slug, (categoryCounts.get(cat.slug) || 0) + 1);
      }
    }

    console.log('');
    console.log('📈 Top categories:');
    const sorted = [...categoryCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15);
    for (const [slug, count] of sorted) {
      console.log(`   ${slug}: ${count}`);
    }
  } finally {
    await pool.end();
  }
}

main().catch((e) => {
  console.error('❌ Error:', e);
  process.exit(1);
});
