// Script to wire in thumbs up/down sentiment from an Excel file to local-db.json
// Usage: node scripts/wire-thumbs-up-down.mjs <excelPath> <dbPath>

import fs from 'fs';
import path from 'path';
import xlsx from 'xlsx';

const [,, excelPath, dbPath] = process.argv;
if (!excelPath || !dbPath) {
  console.error('Usage: node scripts/wire-thumbs-up-down.mjs <excelPath> <dbPath>');
  process.exit(1);
}

const db = JSON.parse(fs.readFileSync(dbPath, 'utf8'));
const wb = xlsx.readFile(excelPath);
const ws = wb.Sheets[wb.SheetNames[0]];
const rows = xlsx.utils.sheet_to_json(ws, { defval: '' });

// Try to match by sent_email_name or approved_document_name
const sentimentMap = {};
for (const row of rows) {
  const email = row.sent_email_name || row['sent_email_name'] || row['Email'] || row['email'] || row['SENT_EMAIL_NAME'];
  const thumbsUp = Number(row.thumbs_up || row['thumbs_up'] || row['Thumbs Up'] || row['THUMBS_UP'] || 0);
  const thumbsDown = Number(row.thumbs_down || row['thumbs_down'] || row['Thumbs Down'] || row['THUMBS_DOWN'] || 0);
  if (email) {
    sentimentMap[email] = { thumbs_up: thumbsUp, thumbs_down: thumbsDown };
  }
}

let updated = 0;
for (const event of db.raw_email_events || []) {
  const email = event.sent_email_name;
  if (email && sentimentMap[email]) {
    event.thumbs_up = sentimentMap[email].thumbs_up;
    event.thumbs_down = sentimentMap[email].thumbs_down;
    updated++;
  }
}

fs.writeFileSync(dbPath, JSON.stringify(db, null, 2));
console.log(`Wired in thumbs up/down for ${updated} emails.`);