#!/usr/bin/env node
/**
 * build-rates.js
 * Converts the UK Skilled Worker going-rates CSV into:
 *   - data/going_rates.json   (bundled in the extension; rates + lookup)
 *   - worker/soc-list.js      (the allowed SOC code/title list the AI must pick from)
 *
 * Usage: node build-rates.js [path-to-csv]   (defaults to data/going_rates.csv)
 */
const fs = require('fs');
const path = require('path');

function parseCSV(text) {
  const rows = []; let row = [], field = '', q = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (q) {
      if (c === '"') { if (text[i + 1] === '"') { field += '"'; i++; } else q = false; }
      else field += c;
    } else if (c === '"') q = true;
    else if (c === ',') { row.push(field); field = ''; }
    else if (c === '\n') { row.push(field); rows.push(row); row = []; field = ''; }
    else if (c !== '\r') field += c;
  }
  if (field.length || row.length) { row.push(field); rows.push(row); }
  return rows;
}

const money = (s) => {
  if (!s) return null;
  const n = parseFloat(String(s).replace(/[£,\s]/g, ''));
  return isNaN(n) ? null : n;
};

const input = process.argv[2] || path.join(__dirname, 'data', 'going_rates.csv');
if (!fs.existsSync(input)) { console.error('✗ CSV not found:', input); process.exit(1); }

const rows = parseCSV(fs.readFileSync(input, 'utf8')).filter(r => r.some(c => c && c.trim()));
const header = rows[0].map(h => h.trim().toLowerCase());
const idx = {
  code: header.findIndex(h => h.includes('code')),
  title: header.findIndex(h => h.includes('job type') || h === 'occupation'),
  related: header.findIndex(h => h.includes('related')),
  annual: header.findIndex(h => h.includes('standard') && h.includes('annual')),
  hourly: header.findIndex(h => h.includes('standard') && h.includes('hourly')),
  lowerAnnual: header.findIndex(h => h.includes('lower') && h.includes('annual')),
  lowerHourly: header.findIndex(h => h.includes('lower') && h.includes('hourly')),
};

const byCode = {};
const socList = [];
for (let i = 1; i < rows.length; i++) {
  const r = rows[i];
  const code = (r[idx.code] || '').trim();
  const title = (r[idx.title] || '').trim();
  if (!code || !title) continue;
  const related = idx.related > -1
    ? (r[idx.related] || '').split(';').map(s => s.trim()).filter(Boolean)
    : [];
  byCode[code] = {
    code, title, related,
    annual: money(r[idx.annual]),
    hourly: money(r[idx.hourly]),
    lowerAnnual: money(r[idx.lowerAnnual]),
    lowerHourly: money(r[idx.lowerHourly]),
  };
  socList.push({ code, title });
}

const meta = {
  source: path.basename(input),
  generatedAt: new Date().toISOString(),
  count: Object.keys(byCode).length,
};

fs.mkdirSync(path.join(__dirname, 'worker'), { recursive: true });
fs.writeFileSync(path.join(__dirname, 'data', 'going_rates.json'), JSON.stringify({ meta, byCode }));
fs.writeFileSync(
  path.join(__dirname, 'worker', 'soc-list.js'),
  '// Auto-generated from the going-rates CSV. Do not edit by hand.\n' +
  'export const SOC_LIST = ' + JSON.stringify(socList) + ';\n'
);

console.log(`✓ ${meta.count} occupations`);
console.log(`  → data/going_rates.json`);
console.log(`  → worker/soc-list.js`);
