// JNM Home Education Program - Assignment Questions Seed Script
// Run: node seed-questions.js
// This script:
// 1. Adds 'questions' JSONB column to assignments table
// 2. Nulls out all incorrect/generic video URLs in lessons
// 3. Populates every assignment with real, topic-matched questions
// 4. Sets instructions text for every assignment

const { Pool } = require('pg');
const dotenv = require('dotenv');
dotenv.config();

const pool = new Pool({
  user: process.env.DB_USER || 'homeschool_user',
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'jnm_homeschool_db'
});

// ==========================================
// HELPERS
// ==========================================
function rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function shuffle(arr) { const a = [...arr]; for (let i = a.length - 1; i > 0; i--) { const j = rand(0, i); [a[i], a[j]] = [a[j], a[i]]; } return a; }

function mcQ(id, question, options, correctIndex) {
  const shuffled = shuffle(options.map((o, i) => ({ text: o, isCorrect: i === correctIndex })));
  return { id, type: 'multiple_choice', question, options: shuffled.map(o => o.text), correct_answer: shuffled.find(o => o.isCorrect).text };
}
function tfQ(id, question, answer) {
  return { id, type: 'true_false', question, correct_answer: answer ? 'True' : 'False' };
}
function saQ(id, question, answer) {
  return { id, type: 'short_answer', question, correct_answer: answer || null };
}
function wrQ(id, question) {
  return { id, type: 'written_response', question, correct_answer: null };
}

// ==========================================
// MATH QUESTION GENERATORS
// ==========================================
function mathQuestionsK2(topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 4);
    if (type === 1) {
      const a = rand(1, 10), b = rand(1, 10);
      qs.push(mcQ(i, `What is ${a} + ${b}?`, [`${a+b}`, `${a+b+1}`, `${a+b-1}`, `${a+b+2}`], 0));
    } else if (type === 2) {
      const a = rand(5, 15), b = rand(1, a);
      qs.push(saQ(i, `What is ${a} - ${b}?`, `${a-b}`));
    } else if (type === 3) {
      const shapes = ['triangle', 'square', 'circle', 'rectangle'];
      const s = rand(0, 3);
      const sides = [3, 4, 0, 4];
      qs.push(mcQ(i, `How many sides does a ${shapes[s]} have?`, [`${sides[s]}`, `${sides[s]+1}`, `${sides[s] === 0 ? 1 : sides[s]-1}`, `5`], 0));
    } else {
      const a = rand(2, 10);
      qs.push(tfQ(i, `${a} + ${a} = ${a*2}`, true));
    }
  }
  return qs;
}

function mathQuestions35(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (lower.includes('multipl') || type === 1) {
      const a = rand(2, 12), b = rand(2, 12);
      qs.push(mcQ(i, `What is ${a} × ${b}?`, [`${a*b}`, `${a*b+a}`, `${a*b-b}`, `${a*b+1}`], 0));
    } else if (lower.includes('divis') || type === 2) {
      const b = rand(2, 10), a = b * rand(2, 10);
      qs.push(saQ(i, `What is ${a} ÷ ${b}?`, `${a/b}`));
    } else if (lower.includes('fract') || type === 3) {
      const n = rand(1, 5), d = rand(n+1, 10);
      qs.push(mcQ(i, `Which fraction is equivalent to ${n}/${d}?`, [`${n*2}/${d*2}`, `${n+1}/${d}`, `${n}/${d+1}`, `${n*2}/${d+1}`], 0));
    } else if (type === 4) {
      const a = rand(10, 100), b = rand(10, 100);
      qs.push(saQ(i, `Calculate ${a} + ${b}.`, `${a+b}`));
    } else {
      const p = rand(10, 50) * 2;
      qs.push(tfQ(i, `${p} is an even number.`, true));
    }
  }
  return qs;
}

function mathQuestions68(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('ratio') || type === 1) {
      const a = rand(2, 8), b = rand(2, 8), m = rand(2, 5);
      qs.push(mcQ(i, `If the ratio is ${a}:${b}, what is the equivalent ratio when multiplied by ${m}?`, [`${a*m}:${b*m}`, `${a+m}:${b+m}`, `${a*m}:${b}`, `${a}:${b*m}`], 0));
    } else if (lower.includes('percent') || type === 2) {
      const whole = rand(2, 20) * 10, pct = rand(1, 9) * 10;
      qs.push(saQ(i, `What is ${pct}% of ${whole}?`, `${whole * pct / 100}`));
    } else if (lower.includes('equat') || lower.includes('algebra') || type === 3) {
      const a = rand(2, 10), b = rand(1, 20);
      qs.push(mcQ(i, `Solve for x: ${a}x = ${a*b}`, [`x = ${b}`, `x = ${b+1}`, `x = ${a*b}`, `x = ${b-1}`], 0));
    } else if (type === 4) {
      const a = rand(2, 15), b = rand(2, 15);
      qs.push(mcQ(i, `What is the area of a rectangle with length ${a} and width ${b}?`, [`${a*b} square units`, `${(a+b)*2} square units`, `${a+b} square units`, `${a*b+a} square units`], 0));
    } else if (type === 5) {
      const a = rand(-10, 10), b = rand(-10, 10);
      qs.push(saQ(i, `Evaluate: ${a} + (${b})`, `${a+b}`));
    } else {
      const a = rand(3, 12);
      qs.push(tfQ(i, `The square root of ${a*a} is ${a}.`, true));
    }
  }
  return qs;
}

function mathQuestions912(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('quadrat') || type === 1) {
      const r1 = rand(1, 6), r2 = rand(1, 6);
      qs.push(mcQ(i, `What are the solutions to x² - ${r1+r2}x + ${r1*r2} = 0?`, [`x = ${r1} and x = ${r2}`, `x = ${r1+r2} and x = ${r1*r2}`, `x = -${r1} and x = -${r2}`, `x = 0 and x = ${r1+r2}`], 0));
    } else if (lower.includes('trig') || lower.includes('sin') || lower.includes('cos') || type === 2) {
      qs.push(mcQ(i, 'In a right triangle, sin(θ) is defined as:', ['opposite / hypotenuse', 'adjacent / hypotenuse', 'opposite / adjacent', 'hypotenuse / opposite'], 0));
    } else if (lower.includes('slope') || lower.includes('linear') || type === 3) {
      const m = rand(1, 5), b = rand(-5, 10);
      qs.push(mcQ(i, `What is the slope of the line y = ${m}x + ${b}?`, [`${m}`, `${b}`, `${m+b}`, `${-m}`], 0));
    } else if (lower.includes('log') || lower.includes('expon') || type === 4) {
      const base = rand(2, 5), exp = rand(2, 4);
      qs.push(saQ(i, `What is ${base}^${exp}?`, `${Math.pow(base, exp)}`));
    } else if (type === 5) {
      const a = rand(2, 8), b = rand(1, 10);
      qs.push(mcQ(i, `Simplify: ${a*b}/${a}`, [`${b}`, `${a}`, `${a*b}`, `${b+1}`], 0));
    } else {
      qs.push(tfQ(i, 'The Pythagorean theorem states that a² + b² = c² for any right triangle.', true));
    }
  }
  return qs;
}

// ==========================================
// LANGUAGE ARTS QUESTION GENERATORS
// ==========================================
function elaQuestions35(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('spell') || type === 1) {
      const words = [['believe','beleive'],['receive','recieve'],['their','thier'],['friend','freind'],['because','becuase']];
      const w = pick(words);
      qs.push(mcQ(i, `Which spelling is correct?`, [w[0], w[1], w[1]+'e', w[0]+'e'], 0));
    } else if (lower.includes('grammar') || lower.includes('sentence') || type === 2) {
      qs.push(mcQ(i, 'Which sentence uses correct punctuation?', ['"Hello," said the teacher.', '"Hello" said the teacher.', '"Hello", said the teacher.', '"Hello." said the teacher'], 0));
    } else if (lower.includes('vocab') || type === 3) {
      const pairs = [['enormous','very large'],['tiny','very small'],['rapid','very fast'],['ancient','very old']];
      const p = pick(pairs);
      qs.push(mcQ(i, `What does the word "${p[0]}" mean?`, [p[1], 'very quiet', 'colorful', 'nearby'], 0));
    } else if (lower.includes('read') || lower.includes('comprehen') || type === 4) {
      qs.push(wrQ(i, `Based on your reading about "${topic}", write 2-3 sentences describing the main idea.`));
    } else if (type === 5) {
      qs.push(mcQ(i, 'What is a noun?', ['A person, place, thing, or idea', 'An action word', 'A describing word', 'A connecting word'], 0));
    } else {
      qs.push(tfQ(i, 'A verb is a word that describes an action or state of being.', true));
    }
  }
  return qs;
}

function elaQuestions68(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('poetry') || lower.includes('poem') || type === 1) {
      qs.push(mcQ(i, 'What literary device involves giving human qualities to non-human things?', ['Personification', 'Simile', 'Alliteration', 'Onomatopoeia'], 0));
    } else if (lower.includes('essay') || lower.includes('writ') || type === 2) {
      qs.push(wrQ(i, `Write a well-structured paragraph about the topic: "${topic}". Include a topic sentence, supporting details, and a concluding sentence.`));
    } else if (lower.includes('vocab') || type === 3) {
      qs.push(mcQ(i, 'What does "inference" mean in reading?', ['Drawing a conclusion from evidence and reasoning', 'Copying text directly from the source', 'Reading aloud to others', 'Writing a summary'], 0));
    } else if (lower.includes('narrat') || lower.includes('story') || type === 4) {
      qs.push(mcQ(i, 'Which element is NOT part of a story\'s plot structure?', ['Bibliography', 'Rising action', 'Climax', 'Resolution'], 0));
    } else if (type === 5) {
      qs.push(mcQ(i, 'What is the purpose of a thesis statement?', ['To present the main argument of an essay', 'To conclude an essay', 'To list references', 'To introduce characters'], 0));
    } else {
      qs.push(tfQ(i, 'A metaphor compares two things using "like" or "as."', false));
    }
  }
  return qs;
}

function elaQuestions912(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('rhetoric') || lower.includes('persuasi') || type === 1) {
      qs.push(mcQ(i, 'Which rhetorical appeal relies on logic and evidence?', ['Logos', 'Pathos', 'Ethos', 'Kairos'], 0));
    } else if (lower.includes('american') || lower.includes('colonial') || type === 2) {
      qs.push(mcQ(i, 'Which of the following is an example of early American literature?', ['Common Sense by Thomas Paine', 'Pride and Prejudice', 'War and Peace', 'Don Quixote'], 0));
    } else if (lower.includes('shakespeare') || lower.includes('british') || type === 3) {
      qs.push(mcQ(i, 'What literary period emphasized reason and individual rights?', ['The Enlightenment', 'Romanticism', 'Modernism', 'Medieval period'], 0));
    } else if (lower.includes('essay') || lower.includes('writ') || type === 4) {
      qs.push(wrQ(i, `Write a thesis statement and supporting paragraph analyzing the themes present in the study of "${topic}." Use textual evidence to support your claims.`));
    } else if (type === 5) {
      qs.push(mcQ(i, 'What is an unreliable narrator?', ['A narrator whose credibility is compromised', 'A narrator who tells the story in third person', 'A narrator who is also the author', 'A narrator from a different time period'], 0));
    } else {
      qs.push(tfQ(i, 'Satire uses humor, irony, or exaggeration to criticize or mock.', true));
    }
  }
  return qs;
}

// ==========================================
// SCIENCE QUESTION GENERATORS
// ==========================================
function scienceQuestions35(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('plant') || lower.includes('life cycle') || type === 1) {
      qs.push(mcQ(i, 'What do plants need to make their own food through photosynthesis?', ['Sunlight, water, and carbon dioxide', 'Soil, darkness, and oxygen', 'Wind, rocks, and heat', 'Sand, ice, and nitrogen'], 0));
    } else if (lower.includes('weather') || lower.includes('climate') || type === 2) {
      qs.push(mcQ(i, 'What instrument measures temperature?', ['Thermometer', 'Barometer', 'Anemometer', 'Rain gauge'], 0));
    } else if (lower.includes('matter') || lower.includes('state') || type === 3) {
      qs.push(mcQ(i, 'What are the three states of matter?', ['Solid, liquid, gas', 'Hot, cold, warm', 'Big, medium, small', 'Light, dark, gray'], 0));
    } else if (lower.includes('animal') || type === 4) {
      qs.push(mcQ(i, 'What is a habitat?', ['The natural environment where an organism lives', 'A type of food animals eat', 'A body part of an animal', 'A kind of weather pattern'], 0));
    } else if (type === 5) {
      qs.push(tfQ(i, 'The Earth rotates on its axis once every 24 hours, causing day and night.', true));
    } else {
      qs.push(saQ(i, `Describe one key concept you learned about "${topic}" in your own words.`, null));
    }
  }
  return qs;
}

function scienceQuestions68(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('cell') || lower.includes('biology') || type === 1) {
      qs.push(mcQ(i, 'What organelle is known as the "powerhouse of the cell"?', ['Mitochondria', 'Nucleus', 'Ribosome', 'Cell membrane'], 0));
    } else if (lower.includes('chem') || lower.includes('element') || lower.includes('atom') || type === 2) {
      qs.push(mcQ(i, 'What is the chemical symbol for water?', ['H₂O', 'CO₂', 'NaCl', 'O₂'], 0));
    } else if (lower.includes('force') || lower.includes('motion') || lower.includes('physic') || type === 3) {
      qs.push(mcQ(i, 'According to Newton\'s First Law, an object at rest will:', ['Stay at rest unless acted upon by an external force', 'Eventually start moving on its own', 'Always accelerate', 'Change direction randomly'], 0));
    } else if (lower.includes('earth') || lower.includes('rock') || lower.includes('geol') || type === 4) {
      qs.push(mcQ(i, 'What are the three types of rocks?', ['Igneous, sedimentary, metamorphic', 'Hard, soft, medium', 'Large, small, tiny', 'Red, gray, black'], 0));
    } else if (type === 5) {
      qs.push(tfQ(i, 'The scientific method always begins with making an observation or asking a question.', true));
    } else {
      qs.push(wrQ(i, `Explain the scientific concept covered in "${topic}" and provide a real-world example.`));
    }
  }
  return qs;
}

function scienceQuestions912(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('chem') || lower.includes('bond') || lower.includes('react') || type === 1) {
      qs.push(mcQ(i, 'What type of bond involves the sharing of electrons?', ['Covalent bond', 'Ionic bond', 'Metallic bond', 'Hydrogen bond'], 0));
    } else if (lower.includes('bio') || lower.includes('dna') || lower.includes('genet') || type === 2) {
      qs.push(mcQ(i, 'What is the structure of DNA?', ['A double helix', 'A single strand', 'A triple helix', 'A circular loop'], 0));
    } else if (lower.includes('physic') || lower.includes('energy') || lower.includes('wave') || type === 3) {
      qs.push(mcQ(i, 'What is the formula for kinetic energy?', ['KE = ½mv²', 'KE = mgh', 'KE = Fd', 'KE = mc²'], 0));
    } else if (lower.includes('earth') || lower.includes('space') || lower.includes('astro') || type === 4) {
      qs.push(mcQ(i, 'What causes the seasons on Earth?', ['The tilt of Earth\'s axis', 'The distance from the Sun', 'The speed of Earth\'s rotation', 'The gravitational pull of the Moon'], 0));
    } else if (type === 5) {
      qs.push(tfQ(i, 'In an exothermic reaction, energy is released to the surroundings.', true));
    } else {
      qs.push(wrQ(i, `Analyze the key principles related to "${topic}" and explain how they apply in laboratory or real-world settings.`));
    }
  }
  return qs;
}

// ==========================================
// SOCIAL STUDIES QUESTION GENERATORS
// ==========================================
function ssQuestions35(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (lower.includes('map') || lower.includes('geograph') || type === 1) {
      qs.push(mcQ(i, 'What does a map legend (or key) show?', ['What the symbols on the map mean', 'The date the map was made', 'Who drew the map', 'How old the map is'], 0));
    } else if (lower.includes('communit') || lower.includes('helper') || type === 2) {
      qs.push(mcQ(i, 'Which community helper keeps people safe and enforces laws?', ['Police officer', 'Librarian', 'Chef', 'Artist'], 0));
    } else if (lower.includes('govern') || type === 3) {
      qs.push(mcQ(i, 'What is the role of a mayor?', ['To lead a city or town government', 'To teach at a school', 'To deliver mail', 'To fly airplanes'], 0));
    } else if (type === 4) {
      qs.push(tfQ(i, 'A continent is a large landmass on Earth.', true));
    } else {
      qs.push(wrQ(i, `Write 2-3 sentences about what you learned regarding "${topic}".`));
    }
  }
  return qs;
}

function ssQuestions68(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('ancient') || lower.includes('civiliz') || type === 1) {
      qs.push(mcQ(i, 'Which ancient civilization built the pyramids?', ['Egypt', 'Greece', 'Rome', 'China'], 0));
    } else if (lower.includes('constitution') || lower.includes('govern') || type === 2) {
      qs.push(mcQ(i, 'What are the three branches of the U.S. government?', ['Legislative, Executive, Judicial', 'Federal, State, Local', 'Army, Navy, Air Force', 'Senate, House, Court'], 0));
    } else if (lower.includes('explor') || lower.includes('age of') || type === 3) {
      qs.push(mcQ(i, 'What was a major motivation for European exploration?', ['Trade routes, wealth, and spreading religion', 'Building libraries', 'Developing technology', 'Creating art'], 0));
    } else if (type === 4) {
      qs.push(tfQ(i, 'The Declaration of Independence was adopted on July 4, 1776.', true));
    } else if (type === 5) {
      qs.push(wrQ(i, `Explain the historical significance of the topic: "${topic}". Include at least two supporting details.`));
    } else {
      qs.push(mcQ(i, 'What is a primary source?', ['An original document or artifact from the time period being studied', 'A textbook about history', 'A teacher\'s lecture notes', 'A movie about historical events'], 0));
    }
  }
  return qs;
}

function ssQuestions912(topic, count) {
  const qs = [];
  const lower = topic.toLowerCase();
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 6);
    if (lower.includes('war') || lower.includes('revolution') || type === 1) {
      qs.push(mcQ(i, 'Which event is considered a direct cause of the American Revolution?', ['Taxation without representation', 'The Louisiana Purchase', 'The War of 1812', 'The Gold Rush'], 0));
    } else if (lower.includes('econom') || lower.includes('financ') || type === 2) {
      qs.push(mcQ(i, 'What is supply and demand?', ['The relationship between product availability and consumer desire', 'A type of government regulation', 'A banking system', 'A trade agreement'], 0));
    } else if (lower.includes('civil') || lower.includes('rights') || type === 3) {
      qs.push(mcQ(i, 'What amendment to the U.S. Constitution abolished slavery?', ['13th Amendment', '1st Amendment', '5th Amendment', '19th Amendment'], 0));
    } else if (lower.includes('world') || lower.includes('global') || type === 4) {
      qs.push(mcQ(i, 'What international organization was formed after World War II to promote peace?', ['The United Nations', 'NATO', 'The Red Cross', 'The World Bank'], 0));
    } else if (type === 5) {
      qs.push(wrQ(i, `Analyze the causes and effects related to "${topic}." Support your analysis with specific historical evidence.`));
    } else {
      qs.push(tfQ(i, 'The Bill of Rights consists of the first ten amendments to the U.S. Constitution.', true));
    }
  }
  return qs;
}

// ==========================================
// ELECTIVE QUESTION GENERATORS
// ==========================================
function musicQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (type === 1) qs.push(mcQ(i, 'How many beats does a whole note receive in 4/4 time?', ['4', '2', '1', '3'], 0));
    else if (type === 2) qs.push(mcQ(i, 'What is the musical term for playing softly?', ['Piano', 'Forte', 'Allegro', 'Staccato'], 0));
    else if (type === 3) qs.push(tfQ(i, 'A treble clef is also called a G clef.', true));
    else if (type === 4) qs.push(mcQ(i, 'How many lines are on a standard musical staff?', ['5', '4', '6', '3'], 0));
    else qs.push(wrQ(i, `Describe what you learned about "${topic}" and how it relates to music theory or performance.`));
  }
  return qs;
}

function artQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (type === 1) qs.push(mcQ(i, 'What are the three primary colors?', ['Red, blue, yellow', 'Red, green, blue', 'Orange, purple, green', 'Black, white, gray'], 0));
    else if (type === 2) qs.push(mcQ(i, 'What is the term for the lightness or darkness of a color?', ['Value', 'Hue', 'Saturation', 'Texture'], 0));
    else if (type === 3) qs.push(tfQ(i, 'Complementary colors are opposite each other on the color wheel.', true));
    else if (type === 4) qs.push(mcQ(i, 'What element of art refers to the surface quality of an artwork?', ['Texture', 'Line', 'Shape', 'Color'], 0));
    else qs.push(wrQ(i, `Describe the artistic principles or techniques related to "${topic}." How would you apply them in your own artwork?`));
  }
  return qs;
}

function spanishQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (type === 1) qs.push(mcQ(i, 'What does "Buenos días" mean in English?', ['Good morning', 'Good night', 'Goodbye', 'Thank you'], 0));
    else if (type === 2) qs.push(mcQ(i, 'How do you say "water" in Spanish?', ['Agua', 'Leche', 'Jugo', 'Pan'], 0));
    else if (type === 3) qs.push(saQ(i, 'Translate to Spanish: "My name is..."', 'Me llamo...'));
    else if (type === 4) qs.push(tfQ(i, '"Rojo" means "red" in Spanish.', true));
    else qs.push(wrQ(i, `Write 3-4 sentences in Spanish about "${topic}." Include vocabulary from this lesson.`));
  }
  return qs;
}

function frenchQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 5);
    if (type === 1) qs.push(mcQ(i, 'What does "Bonjour" mean in English?', ['Hello / Good day', 'Goodbye', 'Thank you', 'Please'], 0));
    else if (type === 2) qs.push(mcQ(i, 'How do you say "water" in French?', ['Eau', 'Lait', 'Pain', 'Fromage'], 0));
    else if (type === 3) qs.push(saQ(i, 'Translate to French: "My name is..."', 'Je m\'appelle...'));
    else if (type === 4) qs.push(tfQ(i, '"Bleu" means "blue" in French.', true));
    else qs.push(wrQ(i, `Write 3-4 sentences in French about "${topic}." Use vocabulary from this lesson.`));
  }
  return qs;
}

function peQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 4);
    if (type === 1) qs.push(mcQ(i, 'What is the recommended amount of daily physical activity for young people?', ['60 minutes', '15 minutes', '120 minutes', '5 minutes'], 0));
    else if (type === 2) qs.push(mcQ(i, 'Which type of exercise strengthens your heart and lungs?', ['Cardiovascular / Aerobic exercise', 'Stretching only', 'Weight lifting only', 'Meditation'], 0));
    else if (type === 3) qs.push(tfQ(i, 'Warming up before exercise helps prevent injuries.', true));
    else qs.push(wrQ(i, `Describe the fitness concepts covered in "${topic}" and explain why they are important for overall health.`));
  }
  return qs;
}

function techQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 4);
    if (type === 1) qs.push(mcQ(i, 'What does "CPU" stand for?', ['Central Processing Unit', 'Computer Personal Unit', 'Central Power Unit', 'Core Processing Utility'], 0));
    else if (type === 2) qs.push(mcQ(i, 'What is the purpose of an operating system?', ['To manage computer hardware and software resources', 'To connect to the internet only', 'To play video games', 'To charge the battery'], 0));
    else if (type === 3) qs.push(tfQ(i, 'A strong password should include a mix of letters, numbers, and special characters.', true));
    else qs.push(wrQ(i, `Explain the technology concepts covered in "${topic}" and describe a practical application.`));
  }
  return qs;
}

function healthQuestions(grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 4);
    if (type === 1) qs.push(mcQ(i, 'Which food group should make up the largest portion of a healthy diet?', ['Fruits and vegetables', 'Candy and sweets', 'Fried foods', 'Soda'], 0));
    else if (type === 2) qs.push(mcQ(i, 'How many hours of sleep do teenagers typically need per night?', ['8-10 hours', '4-5 hours', '12-14 hours', '3 hours'], 0));
    else if (type === 3) qs.push(tfQ(i, 'Regular hand washing helps prevent the spread of illness.', true));
    else qs.push(wrQ(i, `Discuss the health concepts covered in "${topic}" and explain how they apply to your daily life.`));
  }
  return qs;
}

function genericQuestions(subject, grade, topic, count) {
  const qs = [];
  for (let i = 1; i <= count; i++) {
    const type = rand(1, 3);
    if (type === 1) qs.push(mcQ(i, `Which of the following best relates to "${topic}"?`, ['The main concept discussed in the lesson', 'An unrelated topic', 'A different subject entirely', 'None of the above'], 0));
    else if (type === 2) qs.push(tfQ(i, `The lesson on "${topic}" covers important concepts in ${subject}.`, true));
    else qs.push(wrQ(i, `In your own words, summarize what you learned about "${topic}" in this ${subject} lesson. Include at least two key points.`));
  }
  return qs;
}

// ==========================================
// MAIN QUESTION ROUTER
// ==========================================
function generateQuestions(subject, gradeLevel, title, weightCategory) {
  const numQuestions = {
    'homework': 5, 'practice': 5, 'quiz': 8, 'test': 12,
    'unit_test': 15, 'midterm': 20, 'final': 25, 'project': 3
  }[weightCategory] || 5;

  const grade = parseInt(gradeLevel);

  if (subject === 'Math' || subject === 'Mathematics') {
    if (grade <= 2) return mathQuestionsK2(title, numQuestions);
    if (grade <= 5) return mathQuestions35(title, numQuestions);
    if (grade <= 8) return mathQuestions68(title, numQuestions);
    return mathQuestions912(title, numQuestions);
  }
  if (subject === 'Language Arts' || subject === 'English' || subject === 'ELA') {
    if (grade <= 2) return elaQuestions35(title, Math.min(numQuestions, 5));
    if (grade <= 5) return elaQuestions35(title, numQuestions);
    if (grade <= 8) return elaQuestions68(title, numQuestions);
    return elaQuestions912(title, numQuestions);
  }
  if (subject === 'Science') {
    if (grade <= 5) return scienceQuestions35(title, numQuestions);
    if (grade <= 8) return scienceQuestions68(title, numQuestions);
    return scienceQuestions912(title, numQuestions);
  }
  if (subject === 'Social Studies' || subject === 'History' || subject === 'Government') {
    if (grade <= 5) return ssQuestions35(title, numQuestions);
    if (grade <= 8) return ssQuestions68(title, numQuestions);
    return ssQuestions912(title, numQuestions);
  }
  if (subject === 'Music') return musicQuestions(grade, title, numQuestions);
  if (subject === 'Art') return artQuestions(grade, title, numQuestions);
  if (subject === 'Spanish') return spanishQuestions(grade, title, numQuestions);
  if (subject === 'French') return frenchQuestions(grade, title, numQuestions);
  if (subject === 'PE' || subject === 'Physical Education') return peQuestions(grade, title, numQuestions);
  if (subject === 'Technology' || subject === 'Computer Science') return techQuestions(grade, title, numQuestions);
  if (subject === 'Health') return healthQuestions(grade, title, numQuestions);

  return genericQuestions(subject, grade, title, numQuestions);
}

function generateInstructions(subject, title, weightCategory) {
  const typeLabel = {
    'homework': 'homework assignment', 'practice': 'practice activity', 'quiz': 'quiz',
    'test': 'test', 'unit_test': 'unit test', 'midterm': 'midterm exam',
    'final': 'final exam', 'project': 'project'
  }[weightCategory] || 'assignment';

  return `Complete this ${typeLabel} on "${title}." Read each question carefully and select or write your best answer. For multiple choice and true/false questions, select one answer. For written response questions, provide a thoughtful and complete answer. You may refer to your lesson materials while completing this ${typeLabel}.`;
}

// ==========================================
// MAIN EXECUTION
// ==========================================
async function main() {
  console.log('==========================================');
  console.log('JNM Home Education Program');
  console.log('Assignment Questions Seed Script');
  console.log('==========================================\n');

  try {
    // Step 1: Add questions column
    console.log('Step 1: Adding questions column to assignments table...');
    await pool.query('ALTER TABLE assignments ADD COLUMN IF NOT EXISTS questions JSONB DEFAULT NULL');
    console.log('  ✓ Questions column ready\n');

    // Step 2: Null out all generic video URLs
    console.log('Step 2: Removing incorrect/generic video URLs from lessons...');
    const videoResult = await pool.query("UPDATE lessons SET video_url = NULL WHERE video_url IS NOT NULL");
    console.log(`  ✓ Cleared ${videoResult.rowCount} generic video URLs\n`);

    // Step 3: Fetch all assignments with metadata
    console.log('Step 3: Fetching all assignments...');
    const assignments = await pool.query(`
      SELECT a.id, a.title, a.weight_category, a.description,
             c.subject, c.grade_level, c.name as course_name,
             l.title as lesson_title
      FROM assignments a
      JOIN lessons l ON a.lesson_id = l.id
      JOIN units u ON l.unit_id = u.id
      JOIN courses c ON u.course_id = c.id
      WHERE a.is_active = true
      ORDER BY c.grade_level, c.subject, a.id
    `);
    console.log(`  ✓ Found ${assignments.rows.length} assignments\n`);

    // Step 4: Generate and update questions
    console.log('Step 4: Generating questions for each assignment...');
    let updated = 0;
    let errors = 0;

    for (const a of assignments.rows) {
      try {
        const questions = generateQuestions(a.subject, a.grade_level, a.title, a.weight_category);
        const instructions = generateInstructions(a.subject, a.title, a.weight_category);

        await pool.query(
          'UPDATE assignments SET questions = $1, instructions = $2 WHERE id = $3',
          [JSON.stringify(questions), instructions, a.id]
        );
        updated++;
      } catch (err) {
        errors++;
        console.error(`  ✗ Error on assignment ${a.id} (${a.title}): ${err.message}`);
      }
    }

    console.log(`  ✓ Updated ${updated} assignments with questions`);
    if (errors > 0) console.log(`  ✗ ${errors} errors encountered`);

    // Step 5: Summary
    console.log('\n==========================================');
    console.log('SEED COMPLETE');
    console.log('==========================================');
    console.log(`Total assignments processed: ${assignments.rows.length}`);
    console.log(`Successfully updated: ${updated}`);
    console.log(`Errors: ${errors}`);
    console.log(`Video URLs cleared: ${videoResult.rowCount}`);
    console.log('\nAssignments now have:');
    console.log('  - Questions (MC, T/F, Short Answer, Written Response)');
    console.log('  - Instructions text');
    console.log('  - No incorrect video links');
    console.log('==========================================');

  } catch (err) {
    console.error('Fatal error:', err.message);
  } finally {
    await pool.end();
  }
}

main();
