import type { Glossary, GlossaryTermInput } from './types';

export function exportGlossaryToCsv(glossary: Glossary): void {
  const csvContent = generateCsvContent(glossary.terms.map(t => ({ source: t.source, target: t.target })));
  downloadCsv(csvContent, `${glossary.name.replace(/[^a-z0-9]/gi, '_')}.csv`);
}

export function generateCsvContent(terms: GlossaryTermInput[]): string {
  const header = 'source,target';
  const rows = terms
    .filter(t => t.source.trim() && t.target.trim())
    .map(t => `${escapeCsvField(t.source)},${escapeCsvField(t.target)}`);
  return [header, ...rows].join('\n');
}

export function downloadCsv(content: string, filename: string): void {
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

export function parseCsvToTerms(csvText: string): GlossaryTermInput[] {
  const lines = csvText.split(/\r?\n/).filter(line => line.trim());
  if (lines.length === 0) return [];

  const firstLine = lines[0].toLowerCase();
  const hasHeader = firstLine.includes('source') && firstLine.includes('target');
  
  const dataLines = hasHeader ? lines.slice(1) : lines;
  
  const terms: GlossaryTermInput[] = [];
  
  for (const line of dataLines) {
    const parsed = parseCsvLine(line);
    if (parsed.length >= 2) {
      const source = parsed[0].trim();
      const target = parsed[1].trim();
      if (source && target) {
        terms.push({ source, target });
      }
    }
  }
  
  return terms;
}

export async function parseXlsxToTerms(file: File): Promise<GlossaryTermInput[]> {
  const { read, utils } = await import('xlsx');
  const buffer = await file.arrayBuffer();
  const workbook = read(buffer, { type: 'array' });

  const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
  if (!firstSheet) return [];

  const rows: string[][] = utils.sheet_to_json(firstSheet, { header: 1, defval: '' });
  if (rows.length === 0) return [];

  // Detect header row
  const firstRow = rows[0].map(c => String(c).toLowerCase().trim());
  const hasHeader =
    firstRow.some(c => c.includes('source') || c === 'src') &&
    firstRow.some(c => c.includes('target') || c === 'tgt' || c.includes('traduction') || c.includes('cible'));

  const dataRows = hasHeader ? rows.slice(1) : rows;

  const terms: GlossaryTermInput[] = [];
  for (const row of dataRows) {
    const source = String(row[0] ?? '').trim();
    const target = String(row[1] ?? '').trim();
    if (source && target) {
      terms.push({ source, target });
    }
  }

  return terms;
}

export async function parseFileToTerms(file: File): Promise<GlossaryTermInput[]> {
  const ext = file.name.split('.').pop()?.toLowerCase();
  if (ext === 'xlsx' || ext === 'xls' || ext === 'ods') {
    return parseXlsxToTerms(file);
  }
  // CSV / TSV / TXT
  const text = await file.text();
  return parseCsvToTerms(text);
}

function parseCsvLine(line: string): string[] {
  const result: string[] = [];
  let current = '';
  let inQuotes = false;
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i];
    
    if (char === '"') {
      if (inQuotes && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        inQuotes = !inQuotes;
      }
    } else if (char === ',' && !inQuotes) {
      result.push(current);
      current = '';
    } else {
      current += char;
    }
  }
  
  result.push(current);
  return result;
}

function escapeCsvField(field: string): string {
  if (field.includes(',') || field.includes('"') || field.includes('\n')) {
    return `"${field.replace(/"/g, '""')}"`;
  }
  return field;
}
