const fs = require('fs');

function parseCsv(raw) {
  const lines = raw.split('\n').map(l => l.trim()).filter(Boolean);
  if (!lines.length) return [];
  const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, '').toLowerCase());
  return lines.slice(1).map(line => {
    const vals = splitCsvLine(line);
    const row = {};
    headers.forEach((h, i) => { row[h] = (vals[i] || '').replace(/^"|"$/g, '').trim(); });
    return row;
  });
}

function splitCsvLine(line) {
  const result = [];
  let cur = '', inQuote = false;
  for (const ch of line) {
    if (ch === '"') { inQuote = !inQuote; }
    else if (ch === ',' && !inQuote) { result.push(cur); cur = ''; }
    else cur += ch;
  }
  result.push(cur);
  return result;
}

function normalizeRow(row) {
  return {
    name: row['first name'] && row['last name'] ? `${row['first name']} ${row['last name']}` : (row['name'] || ''),
    position: row['position'] || row['title'] || row['role'] || '',
    company: row['company'] || row['organization'] || '',
    linkedin_url: row['url'] || row['linkedin url'] || row['linkedin_url'] || row['profile url'] || '',
    connected_on: row['connected on'] || '',
  };
}

function loadCsv(filePath) {
  const raw = fs.readFileSync(filePath, 'utf8');
  return parseCsv(raw).map(normalizeRow);
}

function findDirectConnections(connections, targetCompany) {
  const target = targetCompany.toLowerCase().trim();
  return connections.filter(c => {
    const co = (c.company || '').toLowerCase().trim();
    return co === target || co.includes(target) || target.includes(co);
  });
}

module.exports = { parseCsv, loadCsv, findDirectConnections };
