#!/usr/bin/env npx tsx
/**
 * Batch QR Code Generator for Hostel Outreach
 * 
 * Usage:
 *   npx tsx scripts/generate-hostel-qr.ts                    # Generate all from default list
 *   npx tsx scripts/generate-hostel-qr.ts --batch feb26      # Custom batch ID
 *   npx tsx scripts/generate-hostel-qr.ts --single "Wake Up! Sydney" --city sydney
 *   npx tsx scripts/generate-hostel-qr.ts --csv hostels.csv  # From CSV (name,city columns)
 * 
 * Output: public/qr/hostel-<slug>-<city>.png
 */

import { writeFileSync, mkdirSync, existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { buildSignupUrl, generateQRCodeBuffer, type QRCampaignParams } from '../src/lib/qr-code';

// Default hostel list — Sydney/Newcastle/Melbourne rollout
const DEFAULT_HOSTELS: Omit<QRCampaignParams, 'batch_id'>[] = [
  // Sydney
  { hostel_name: 'Wake Up! Sydney', city: 'sydney' },
  { hostel_name: 'YHA Sydney Central', city: 'sydney' },
  { hostel_name: 'Base Sydney', city: 'sydney' },
  { hostel_name: 'Railway Square YHA', city: 'sydney' },
  { hostel_name: 'Sydney Harbour YHA', city: 'sydney' },
  { hostel_name: 'Bounce Sydney', city: 'sydney' },
  { hostel_name: 'Mad Monkey Coogee', city: 'sydney' },
  { hostel_name: 'Mad Monkey Kings Cross', city: 'sydney' },
  { hostel_name: 'Asylum Sydney', city: 'sydney' },
  { hostel_name: 'Summer House Kings Cross', city: 'sydney' },
  { hostel_name: 'Jolly Swagman Backpackers', city: 'sydney' },
  { hostel_name: 'Sydney Backpackers', city: 'sydney' },
  // Newcastle
  { hostel_name: 'Backpackers Newcastle', city: 'newcastle' },
  { hostel_name: 'Newcastle Beach YHA', city: 'newcastle' },
  { hostel_name: 'Stockton Beach Holiday Park', city: 'newcastle' },
  // Melbourne
  { hostel_name: 'United Backpackers Melbourne', city: 'melbourne' },
  { hostel_name: 'Discovery Melbourne', city: 'melbourne' },
  { hostel_name: 'YHA Melbourne Central', city: 'melbourne' },
  { hostel_name: 'Base Melbourne', city: 'melbourne' },
  { hostel_name: 'Melbourne Central YHA', city: 'melbourne' },
  { hostel_name: 'Flinders Backpackers', city: 'melbourne' },
  { hostel_name: 'United Backpackers St Kilda', city: 'melbourne' },
  { hostel_name: 'Bunkhouse Melbourne', city: 'melbourne' },
  { hostel_name: 'Melbourne Metro YHA', city: 'melbourne' },
  { hostel_name: 'Nomads Melbourne', city: 'melbourne' },
  { hostel_name: 'Urban Central Accommodation', city: 'melbourne' },
  { hostel_name: 'Space Hotel Melbourne', city: 'melbourne' },
  { hostel_name: 'The Nunnery', city: 'melbourne' },
  { hostel_name: 'St Kilda Backpackers', city: 'melbourne' },
  { hostel_name: 'Greenhouse Backpackers', city: 'melbourne' },
  { hostel_name: 'Home at the Mansion', city: 'melbourne' },
  { hostel_name: 'All Nations Backpackers', city: 'melbourne' },
  // Extras (Gold Coast / Brisbane if expanding)
  { hostel_name: 'Bunk Backpackers Brisbane', city: 'brisbane' },
  { hostel_name: 'Somewhere To Stay Brisbane', city: 'brisbane' },
  { hostel_name: 'Budds in Surfers', city: 'gold-coast' },
  { hostel_name: 'Sleeping Inn Surfers', city: 'gold-coast' },
  { hostel_name: 'Surfers Paradise YHA', city: 'gold-coast' },
];

function slugify(name: string): string {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}

function parseArgs(): { batchId: string; single?: { name: string; city: string }; csv?: string } {
  const args = process.argv.slice(2);
  let batchId = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  let single: { name: string; city: string } | undefined;
  let csv: string | undefined;

  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--batch' && args[i + 1]) {
      batchId = args[++i];
    } else if (args[i] === '--single' && args[i + 1]) {
      const name = args[++i];
      const city = args[i + 1] === '--city' ? args[(i += 2)] : 'unknown';
      single = { name, city };
    } else if (args[i] === '--csv' && args[i + 1]) {
      csv = args[++i];
    }
  }

  return { batchId, single, csv };
}

function loadFromCsv(csvPath: string): Omit<QRCampaignParams, 'batch_id'>[] {
  const content = readFileSync(csvPath, 'utf-8');
  const lines = content.trim().split('\n');
  // Skip header if present
  const start = lines[0].toLowerCase().includes('name') ? 1 : 0;
  
  return lines.slice(start).map(line => {
    const [hostel_name, city] = line.split(',').map(s => s.trim().replace(/^"|"$/g, ''));
    return { hostel_name, city: city || 'unknown' };
  }).filter(h => h.hostel_name);
}

async function main() {
  const { batchId, single, csv } = parseArgs();
  const outDir = join(process.cwd(), 'public', 'qr');
  
  if (!existsSync(outDir)) {
    mkdirSync(outDir, { recursive: true });
  }

  let hostels: Omit<QRCampaignParams, 'batch_id'>[];

  if (single) {
    hostels = [{ hostel_name: single.name, city: single.city }];
  } else if (csv) {
    hostels = loadFromCsv(csv);
  } else {
    hostels = DEFAULT_HOSTELS;
  }

  console.log(`\n🔨 Generating QR codes for ${hostels.length} hostels (batch: ${batchId})\n`);

  const manifest: Array<{ hostel: string; city: string; file: string; url: string }> = [];

  for (const hostel of hostels) {
    const params: QRCampaignParams = { ...hostel, batch_id: batchId };
    const slug = slugify(hostel.hostel_name);
    const filename = `hostel-${slug}-${hostel.city}.png`;
    const filepath = join(outDir, filename);
    const url = buildSignupUrl(params);

    const buffer = await generateQRCodeBuffer(params, {
      size: 800,            // High-res for print (800px at 300dpi ≈ 2.7in)
      errorCorrectionLevel: 'H',
      margin: 2,
    });

    writeFileSync(filepath, buffer);
    manifest.push({ hostel: hostel.hostel_name, city: hostel.city, file: filename, url });
    console.log(`  ✅ ${hostel.hostel_name} (${hostel.city}) → ${filename}`);
  }

  // Write manifest for tracking
  const manifestPath = join(outDir, `manifest-${batchId}.json`);
  writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
  console.log(`\n📋 Manifest: ${manifestPath}`);

  // Summary by city
  const cities = [...new Set(hostels.map(h => h.city))];
  console.log(`\n📊 Summary:`);
  for (const city of cities) {
    const count = hostels.filter(h => h.city === city).length;
    console.log(`   ${city}: ${count} hostels`);
  }
  console.log(`   Total: ${hostels.length} QR codes generated`);
  console.log(`   Output: public/qr/\n`);
}

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