import type { ParsedCsvData } from '../../types/auto-group' function parseCSVLine(line: string, delimiter: 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 === delimiter && !inQuotes) { result.push(current.trim()) current = '' } else { current += char } } result.push(current.trim()) return result } export function parseCSV(text: string): ParsedCsvData { const lines = text.trim().split('\n') if (lines.length < 2) throw new Error('CSV must have at least a header and one data row') const firstLine = lines[0] const csvDelimiter = firstLine.includes('\t') ? '\t' : ',' const headers = parseCSVLine(firstLine, csvDelimiter) const rows: Record[] = [] for (let i = 1; i < lines.length; i++) { const values = parseCSVLine(lines[i], csvDelimiter) if (values.length !== headers.length) continue const row: Record = {} headers.forEach((h, idx) => { row[h] = values[idx] }) rows.push(row) } const sampleKeywords = ['sample', 'name', 'id', 'sample_name', 'samplename', 'file name', 'filename', 'file_name'] const sampleColumn = headers.find(h => sampleKeywords.includes(h.toLowerCase())) ?? headers[0] return { columns: headers, rows, sampleColumn, delimiter: csvDelimiter } }