const fs   = require('fs');
const path = require('path');
const db   = require('./db');

const dataDir = path.join(__dirname, '../../data');
const files   = fs.readdirSync(dataDir).filter(f => f.endsWith('.json'));

for (const file of files) {
  const data = JSON.parse(fs.readFileSync(path.join(dataDir, file), 'utf8'));
  console.log(`\nSeeding: ${file} (subject: ${data.subject})`);

  const subject = db.prepare('SELECT id FROM subjects WHERE slug = ?').get(data.subject);
  if (!subject) {
    console.error(`Subject "${data.subject}" not found. Run migrate first.`);
    continue;
  }
  const subject_id = subject.id;

  /* topics */
  const topicMap = {};
  const insertTopic = db.prepare(
    'INSERT OR IGNORE INTO topics (subject_id, name, order_index) VALUES (?, ?, ?)'
  );
  for (const t of data.topics) {
    insertTopic.run(subject_id, t.name, t.order);
    const row = db.prepare('SELECT id FROM topics WHERE subject_id = ? AND name = ?')
                  .get(subject_id, t.name);
    topicMap[t.name] = row.id;
  }

  /* questions + options inside a transaction (idempotent — skip existing by text) */
  const checkQ = db.prepare('SELECT id FROM questions WHERE subject_id = ? AND text = ?');
  const insertQ = db.prepare(
    'INSERT INTO questions (subject_id, topic_id, text, difficulty, explanation) VALUES (?, ?, ?, ?, ?)'
  );
  const insertO = db.prepare(
    'INSERT INTO options (question_id, text, is_correct, order_index) VALUES (?, ?, ?, ?)'
  );

  let added = 0, skipped = 0;
  db.exec('BEGIN');
  try {
    for (const q of data.questions) {
      if (checkQ.get(subject_id, q.text)) { skipped++; continue; }
      const topic_id = topicMap[q.topic] ?? null;
      insertQ.run(subject_id, topic_id, q.text, q.difficulty, q.explanation ?? null);
      const { id: question_id } = db.prepare('SELECT last_insert_rowid() AS id').get();
      for (let i = 0; i < q.options.length; i++) {
        insertO.run(question_id, q.options[i], i === q.answer ? 1 : 0, i);
      }
      process.stdout.write('.');
      added++;
    }
    db.exec('COMMIT');
  } catch (err) {
    db.exec('ROLLBACK');
    throw err;
  }

  console.log(`\n✓ Добавлено: ${added}, пропущено (уже есть): ${skipped}`);
}

console.log('\nSeed complete.');
