// Toplu yapıştırma ayrıştırıcısı.
// Desteklenen biçimler:
//   1) Satır satır serbest metin:
//        15.11 | kilo 125 | adım 7200 | kcal 2100 | P 150 Y 70 K 200 | not: bacak günü
//        16.11.2026 kg 124,6 adım 10.200 kalori 2.050 protein 160
//   2) Başlıklı CSV (virgül, noktalı virgül veya sekme ile):
//        tarih;kilo;adim;kalori;protein;yag;karbonhidrat
//        15.11.2026;125,0;7200;2100;150;70;200

export type ParsedEntry = {
  day: string;
  weight: number | null;
  steps: number | null;
  calories: number | null;
  protein: number | null;
  fat: number | null;
  carbs: number | null;
  note: string | null;
};

export type ParseResult = { entries: ParsedEntry[]; errors: { line: number; text: string; reason: string }[] };

type Field = 'weight' | 'steps' | 'calories' | 'protein' | 'fat' | 'carbs' | 'note' | 'day';

const ALIASES: Record<string, Field> = {
  tarih: 'day', gun: 'day', 'gün': 'day', date: 'day', day: 'day',
  kilo: 'weight', kg: 'weight', agirlik: 'weight', 'ağırlık': 'weight', weight: 'weight',
  adim: 'steps', 'adım': 'steps', steps: 'steps', step: 'steps',
  kalori: 'calories', kcal: 'calories', cal: 'calories', calories: 'calories',
  p: 'protein', protein: 'protein', pro: 'protein',
  y: 'fat', yag: 'fat', 'yağ': 'fat', fat: 'fat',
  k: 'carbs', karb: 'carbs', karbonhidrat: 'carbs', carb: 'carbs', carbs: 'carbs', kh: 'carbs',
  not: 'note', note: 'note', notlar: 'note',
};

const norm = (s: string) => s.trim().toLocaleLowerCase('tr-TR').replace(/\.$/, '');

/** "85,4" / "85.4" → 85.4 */
function toDecimal(raw: string): number | null {
  const s = raw.trim().replace(',', '.');
  if (!/^\d+(\.\d+)?$/.test(s)) return null;
  return Number(s);
}

/** "10.200" / "10,200" / "10200" → 10200 */
function toInt(raw: string): number | null {
  const s = raw.trim();
  if (/^\d{1,3}([.,]\d{3})+$/.test(s)) return Number(s.replace(/[.,]/g, ''));
  if (/^\d+$/.test(s)) return Number(s);
  if (/^\d+[.,]\d+$/.test(s)) return Math.round(Number(s.replace(',', '.')));
  return null;
}

function pad(n: number) {
  return String(n).padStart(2, '0');
}

/** Tarihi YYYY-MM-DD yapar. Yıl yoksa: bugünden 31 günden fazla ilerideyse geçen yıl sayılır. */
export function parseDay(raw: string, today: string): string | null {
  const s = raw.trim();
  let y: number | null = null, m: number, d: number;
  let mt = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
  if (mt) {
    y = +mt[1]; m = +mt[2]; d = +mt[3];
  } else {
    mt = s.match(/^(\d{1,2})[./](\d{1,2})(?:[./](\d{2}|\d{4}))?$/);
    if (!mt) return null;
    d = +mt[1]; m = +mt[2];
    if (mt[3]) y = mt[3].length === 2 ? 2000 + +mt[3] : +mt[3];
  }
  if (m < 1 || m > 12 || d < 1 || d > 31) return null;
  if (y === null) {
    const ty = +today.slice(0, 4);
    y = ty;
    const candidate = Date.UTC(y, m - 1, d);
    if (candidate - Date.parse(today + 'T00:00:00Z') > 31 * 86_400_000) y = ty - 1;
  }
  const dt = new Date(Date.UTC(y, m - 1, d));
  if (dt.getUTCMonth() !== m - 1) return null; // 31.02 gibi
  return `${y}-${pad(m)}-${pad(d)}`;
}

function setValue(e: ParsedEntry, field: Field, raw: string): boolean {
  if (field === 'note') {
    e.note = raw.trim() || null;
    return true;
  }
  if (field === 'day') return false;
  if (field === 'weight') {
    const v = toDecimal(raw);
    if (v === null || v < 20 || v > 400) return false;
    e.weight = v;
    return true;
  }
  const v = toInt(raw);
  if (v === null) return false;
  e[field] = v;
  return true;
}

const empty = (day: string): ParsedEntry => ({ day, weight: null, steps: null, calories: null, protein: null, fat: null, carbs: null, note: null });

function parseFreeLine(line: string, today: string): ParsedEntry | string {
  let rest = line.trim();
  // not: … satırın sonuna kadar
  let note: string | null = null;
  const noteMatch = rest.match(/(?:^|\|)\s*(?:not|note)\s*:\s*(.*)$/i);
  if (noteMatch) {
    note = noteMatch[1].replace(/\|/g, ' ').trim() || null;
    rest = rest.slice(0, noteMatch.index);
  }
  const dateMatch = rest.match(/^\s*(\d{4}-\d{1,2}-\d{1,2}|\d{1,2}[./]\d{1,2}(?:[./]\d{2,4})?)/);
  if (!dateMatch) return 'Satır bir tarihle başlamıyor (ör. 15.11)';
  const day = parseDay(dateMatch[1], today);
  if (!day) return `Tarih anlaşılamadı: ${dateMatch[1]}`;
  rest = rest.slice(dateMatch[0].length);
  const e = empty(day);
  e.note = note;

  // "125 kg" → kilo
  rest = rest.replace(/(\d+(?:[.,]\d+)?)\s*kg\b/gi, (_m, n) => ` kilo ${n} `);

  const re = /([a-zçğıöşüA-ZÇĞİÖŞÜ]+)\s*[:=]?\s*(\d[\d.,]*)/g;
  let found = 0;
  for (const m of rest.matchAll(re)) {
    const field = ALIASES[norm(m[1])];
    if (!field) return `Bilinmeyen alan: ${m[1]}`;
    if (!setValue(e, field, m[2])) return `Değer anlaşılamadı: ${m[1]} ${m[2]}`;
    found++;
  }
  if (!found && !note) return 'Bu satırda hiç değer yok';
  return e;
}

function splitCsv(line: string, sep: string): string[] {
  return line.split(sep).map((c) => c.trim().replace(/^"(.*)"$/, '$1'));
}

export function parseBulk(text: string, today: string): ParseResult {
  const lines = text.split(/\r?\n/).map((l) => l.trim());
  const entries: ParsedEntry[] = [];
  const errors: ParseResult['errors'] = [];
  const firstIdx = lines.findIndex((l) => l.length > 0);
  if (firstIdx === -1) return { entries, errors };

  const header = lines[firstIdx];
  const sep = header.includes('\t') ? '\t' : header.includes(';') ? ';' : ',';
  const headerCells = splitCsv(header, sep).map(norm);
  const isCsv = headerCells.length > 1 && headerCells.some((c) => ALIASES[c] === 'day');

  if (isCsv) {
    const fields = headerCells.map((c) => ALIASES[c] ?? null);
    lines.slice(firstIdx + 1).forEach((line, i) => {
      if (!line) return;
      const lineNo = firstIdx + i + 2;
      const cells = splitCsv(line, sep);
      const dayIdx = fields.indexOf('day');
      const day = parseDay(cells[dayIdx] ?? '', today);
      if (!day) return errors.push({ line: lineNo, text: line, reason: 'Tarih anlaşılamadı' });
      const e = empty(day);
      for (let c = 0; c < fields.length; c++) {
        const f = fields[c];
        const raw = cells[c] ?? '';
        if (!f || f === 'day' || raw === '') continue;
        if (!setValue(e, f, raw)) return errors.push({ line: lineNo, text: line, reason: `Değer anlaşılamadı: ${headerCells[c]} = ${raw}` });
      }
      entries.push(e);
    });
  } else {
    lines.forEach((line, i) => {
      if (!line || line.startsWith('#')) return;
      const r = parseFreeLine(line, today);
      if (typeof r === 'string') errors.push({ line: i + 1, text: line, reason: r });
      else entries.push(r);
    });
  }

  // Aynı gün birden fazla yazıldıysa sonuncusu geçerli.
  const byDay = new Map<string, ParsedEntry>();
  for (const e of entries) byDay.set(e.day, e);
  return { entries: [...byDay.values()].sort((a, b) => (a.day < b.day ? -1 : 1)), errors };
}
