const fs = require('node:fs');
const path = require('node:path');
const Papa = require('papaparse');
const { PrismaClient } = require('../app/generated/prisma');

function getField(row, candidates) {
  for (const key of candidates) {
    if (key in row && row[key] !== undefined && row[key] !== null && String(row[key]).trim() !== '') {
      return row[key];
    }
  }
  return undefined;
}

async function main() {
  const prisma = new PrismaClient();
  const yearFilter = process.argv[2] ? Number(process.argv[2]) : null;
  const csvPath = path.resolve(process.cwd(), 'datas/allview.csv');
  if (!fs.existsSync(csvPath)) {
    console.error('datas/allview.csv not found');
    process.exit(1);
  }
  const csv = fs.readFileSync(csvPath, 'utf8');
  const parsed = Papa.parse(csv, { header: true, skipEmptyLines: true });
  if (parsed.errors && parsed.errors.length) {
    console.error('CSV parse errors:', parsed.errors);
    process.exit(1);
  }

  const minDate = new Date('2020-01-01');
  let ok = 0, bad = 0;
  for (const r of parsed.data) {
    const dateStr = String(getField(r, ['날짜', 'Date', 'date', 'DATE']) || '').trim();
    const contented = String(getField(r, ['콘텐츠', 'Contented', 'contented', 'Content', 'content', 'Id', 'ID']) || '').trim();
    const viewsRaw = getField(r, ['조회수', 'Validviewday', 'validViewDay', 'validViews', 'views', 'Views']);
    const v = Number(viewsRaw ?? 0);
    const d = new Date(dateStr);
    if (!dateStr || !contented || isNaN(d.getTime()) || d < minDate) { bad++; continue; }
    if (yearFilter && d.getFullYear() !== yearFilter) { bad++; continue; }

    await prisma.viewPerDay.upsert({
      where: { date_contented: { date: d, contented } },
      update: { validViewDay: v },
      create: { date: d, contented, validViewDay: v },
    });
    ok++;
  }
  await prisma.$disconnect();
  console.log(`ViewPerDay seeded from allview.csv${yearFilter?` (year=${yearFilter})`:''}: ok=${ok}, skipped/bad=${bad}`);
}

main().catch((e) => { console.error(e); process.exit(1); });


