// JNM Home Education Program - FULL K-12 Curriculum Seed
// Covers Grades 1-12, all core subjects + electives
// All video links are Khan Academy (free, verified, age-appropriate)

const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
require('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'
});

// Khan Academy base URLs by subject and grade
const KA = {
  math: {
    1: 'https://www.khanacademy.org/math/cc-1st-grade-math',
    2: 'https://www.khanacademy.org/math/cc-2nd-grade-math',
    3: 'https://www.khanacademy.org/math/cc-third-grade-math',
    4: 'https://www.khanacademy.org/math/cc-fourth-grade-math',
    5: 'https://www.khanacademy.org/math/cc-fifth-grade-math',
    6: 'https://www.khanacademy.org/math/cc-sixth-grade-math',
    7: 'https://www.khanacademy.org/math/cc-seventh-grade-math',
    8: 'https://www.khanacademy.org/math/cc-eighth-grade-math',
    9: 'https://www.khanacademy.org/math/algebra',
    10: 'https://www.khanacademy.org/math/geometry',
    11: 'https://www.khanacademy.org/math/algebra2',
    12: 'https://www.khanacademy.org/math/precalculus'
  },
  ela: {
    1: 'https://www.khanacademy.org/ela/cc-2nd-reading-vocab',
    2: 'https://www.khanacademy.org/ela/cc-2nd-reading-vocab',
    3: 'https://www.khanacademy.org/ela/cc-3rd-reading-vocab',
    4: 'https://www.khanacademy.org/ela/cc-4th-reading-vocab',
    5: 'https://www.khanacademy.org/ela/cc-5th-reading-vocab',
    6: 'https://www.khanacademy.org/ela/cc-6th-reading-vocab',
    7: 'https://www.khanacademy.org/ela/cc-7th-reading-vocab',
    8: 'https://www.khanacademy.org/ela/cc-8th-reading-vocab',
    9: 'https://www.khanacademy.org/ela/cc-8th-reading-vocab',
    10: 'https://www.khanacademy.org/ela/cc-8th-reading-vocab',
    11: 'https://www.khanacademy.org/ela/cc-8th-reading-vocab',
    12: 'https://www.khanacademy.org/ela/cc-8th-reading-vocab'
  },
  science: {
    1: 'https://www.khanacademy.org/science/biology',
    2: 'https://www.khanacademy.org/science/biology',
    3: 'https://www.khanacademy.org/science/biology',
    4: 'https://www.khanacademy.org/science/biology',
    5: 'https://www.khanacademy.org/science/biology',
    6: 'https://www.khanacademy.org/science/biology',
    7: 'https://www.khanacademy.org/science/biology',
    8: 'https://www.khanacademy.org/science/physics',
    9: 'https://www.khanacademy.org/science/biology',
    10: 'https://www.khanacademy.org/science/chemistry',
    11: 'https://www.khanacademy.org/science/physics',
    12: 'https://www.khanacademy.org/science/cosmology-and-astronomy'
  },
  ss: {
    1: 'https://www.khanacademy.org/humanities/us-history',
    2: 'https://www.khanacademy.org/humanities/us-history',
    3: 'https://www.khanacademy.org/humanities/us-history',
    4: 'https://www.khanacademy.org/humanities/us-history',
    5: 'https://www.khanacademy.org/humanities/us-history',
    6: 'https://www.khanacademy.org/humanities/world-history',
    7: 'https://www.khanacademy.org/humanities/world-history',
    8: 'https://www.khanacademy.org/humanities/us-history',
    9: 'https://www.khanacademy.org/humanities/world-history',
    10: 'https://www.khanacademy.org/humanities/us-history',
    11: 'https://www.khanacademy.org/humanities/us-government-and-civics',
    12: 'https://www.khanacademy.org/humanities/world-history'
  }
};

// Full K-12 curriculum structure
const FULL_CURRICULUM = {
  1: {
    Math: [
      { unit: 'Counting and Numbers', lessons: ['Counting to 20', 'Comparing Numbers', 'Number Patterns'] },
      { unit: 'Addition Basics', lessons: ['Adding Within 10', 'Adding Within 20', 'Addition Word Problems'] },
      { unit: 'Subtraction Basics', lessons: ['Subtracting Within 10', 'Subtracting Within 20', 'Subtraction Word Problems'] },
      { unit: 'Shapes and Measurement', lessons: ['Basic Shapes', 'Measuring Length', 'Telling Time to the Hour'] }
    ],
    'Language Arts': [
      { unit: 'Phonics and Letter Sounds', lessons: ['Letter Sounds A-M', 'Letter Sounds N-Z', 'Consonant Blends'] },
      { unit: 'Sight Words and Reading', lessons: ['Common Sight Words', 'Reading Simple Sentences', 'Reading Comprehension'] },
      { unit: 'Writing Basics', lessons: ['Writing Letters', 'Writing Words', 'Writing Simple Sentences'] },
      { unit: 'Grammar Foundations', lessons: ['Nouns', 'Verbs', 'Capitalization and Punctuation'] }
    ],
    Science: [
      { unit: 'Living Things', lessons: ['Plants and Animals', 'Animal Habitats', 'Life Cycles'] },
      { unit: 'Weather and Seasons', lessons: ['Types of Weather', 'Four Seasons', 'Weather Patterns'] },
      { unit: 'Earth and Space', lessons: ['Day and Night', 'Sun Moon and Stars', 'Earth Materials'] }
    ],
    'Social Studies': [
      { unit: 'My Community', lessons: ['Community Helpers', 'Rules and Laws', 'Being a Good Citizen'] },
      { unit: 'Maps and Geography', lessons: ['Maps and Directions', 'Land and Water', 'My Neighborhood'] },
      { unit: 'American Symbols', lessons: ['The Flag', 'National Holidays', 'Famous Americans'] }
    ]
  },
  2: {
    Math: [
      { unit: 'Place Value', lessons: ['Ones and Tens', 'Hundreds', 'Comparing Three-Digit Numbers'] },
      { unit: 'Addition and Subtraction', lessons: ['Adding Two-Digit Numbers', 'Subtracting Two-Digit Numbers', 'Word Problems'] },
      { unit: 'Measurement', lessons: ['Measuring in Inches', 'Measuring in Centimeters', 'Time to Nearest 5 Minutes'] },
      { unit: 'Money and Data', lessons: ['Counting Coins', 'Making Change', 'Reading Graphs'] }
    ],
    'Language Arts': [
      { unit: 'Reading Fluency', lessons: ['Reading with Expression', 'Building Vocabulary', 'Story Elements'] },
      { unit: 'Writing Paragraphs', lessons: ['Topic Sentences', 'Supporting Details', 'Conclusion Sentences'] },
      { unit: 'Grammar', lessons: ['Adjectives', 'Adverbs', 'Complete Sentences'] },
      { unit: 'Spelling and Vocabulary', lessons: ['Word Families', 'Prefixes and Suffixes', 'Context Clues'] }
    ],
    Science: [
      { unit: 'Matter', lessons: ['Solids Liquids and Gases', 'Properties of Matter', 'Changes in Matter'] },
      { unit: 'Force and Motion', lessons: ['Pushes and Pulls', 'Speed and Direction', 'Simple Machines'] },
      { unit: 'Life Cycles', lessons: ['Plant Life Cycles', 'Animal Life Cycles', 'Butterfly Metamorphosis'] }
    ],
    'Social Studies': [
      { unit: 'Geography', lessons: ['Continents and Oceans', 'Map Skills', 'Natural Resources'] },
      { unit: 'History', lessons: ['Past Present and Future', 'Important Historical Figures', 'Timeline of Events'] },
      { unit: 'Economics', lessons: ['Needs vs Wants', 'Goods and Services', 'Saving and Spending'] }
    ]
  },
  3: {
    Math: [
      { unit: 'Multiplication', lessons: ['Multiplication Concepts', 'Times Tables 1-5', 'Times Tables 6-12'] },
      { unit: 'Division', lessons: ['Division Concepts', 'Division Facts', 'Division Word Problems'] },
      { unit: 'Fractions', lessons: ['Understanding Fractions', 'Comparing Fractions', 'Fractions on a Number Line'] },
      { unit: 'Geometry', lessons: ['Area and Perimeter', 'Types of Angles', 'Symmetry'] }
    ],
    'Language Arts': [
      { unit: 'Reading Comprehension', lessons: ['Main Idea and Details', 'Making Inferences', 'Summarizing'] },
      { unit: 'Writing', lessons: ['Narrative Writing', 'Informational Writing', 'Opinion Writing'] },
      { unit: 'Grammar', lessons: ['Subject-Verb Agreement', 'Pronouns', 'Conjunctions'] },
      { unit: 'Research Skills', lessons: ['Using a Dictionary', 'Finding Information', 'Taking Notes'] }
    ],
    Science: [
      { unit: 'Forces and Motion', lessons: ['Balanced and Unbalanced Forces', 'Magnets', 'Gravity'] },
      { unit: 'Ecosystems', lessons: ['Food Chains', 'Habitats', 'Adaptations'] },
      { unit: 'Weather', lessons: ['Water Cycle', 'Cloud Types', 'Severe Weather'] }
    ],
    'Social Studies': [
      { unit: 'Communities', lessons: ['Urban Rural and Suburban', 'Local Government', 'Community Resources'] },
      { unit: 'Geography', lessons: ['Regions of the US', 'Physical Features', 'Human Geography'] },
      { unit: 'Economics', lessons: ['Supply and Demand', 'Producers and Consumers', 'Trade'] }
    ]
  },
  4: {
    Math: [
      { unit: 'Multi-Digit Operations', lessons: ['Multi-Digit Multiplication', 'Long Division', 'Estimation'] },
      { unit: 'Fractions and Decimals', lessons: ['Equivalent Fractions', 'Adding Fractions', 'Introduction to Decimals'] },
      { unit: 'Measurement', lessons: ['Unit Conversion', 'Area of Rectangles', 'Perimeter Problems'] },
      { unit: 'Patterns and Algebra', lessons: ['Number Patterns', 'Input-Output Tables', 'Order of Operations'] }
    ],
    'Language Arts': [
      { unit: 'Literature', lessons: ['Fiction vs Nonfiction', 'Character Analysis', 'Theme and Moral'] },
      { unit: 'Writing', lessons: ['Essay Structure', 'Descriptive Writing', 'Research Reports'] },
      { unit: 'Grammar', lessons: ['Complex Sentences', 'Quotation Marks', 'Homophones'] },
      { unit: 'Speaking', lessons: ['Oral Presentations', 'Discussion Skills', 'Active Listening'] }
    ],
    Science: [
      { unit: 'Energy', lessons: ['Forms of Energy', 'Energy Transfer', 'Electricity'] },
      { unit: 'Earth Science', lessons: ['Rocks and Minerals', 'Erosion and Weathering', 'Fossils'] },
      { unit: 'Life Science', lessons: ['Plant Adaptations', 'Animal Adaptations', 'Food Webs'] }
    ],
    'Social Studies': [
      { unit: 'Nevada History', lessons: ['Native Americans of Nevada', 'Nevada Statehood', 'Nevada Geography'] },
      { unit: 'US Regions', lessons: ['Northeast and Southeast', 'Midwest and Southwest', 'West Region'] },
      { unit: 'Exploration', lessons: ['European Explorers', 'Age of Discovery', 'Impact on Native Peoples'] }
    ]
  },
  5: {
    Math: [
      { unit: 'Decimals', lessons: ['Decimal Place Value', 'Adding and Subtracting Decimals', 'Multiplying Decimals'] },
      { unit: 'Fractions', lessons: ['Multiplying Fractions', 'Dividing Fractions', 'Mixed Numbers'] },
      { unit: 'Volume and Measurement', lessons: ['Volume of Rectangular Prisms', 'Converting Units', 'Metric System'] },
      { unit: 'Coordinate Planes', lessons: ['Plotting Points', 'Ordered Pairs', 'Graphing Patterns'] }
    ],
    'Language Arts': [
      { unit: 'Literature Analysis', lessons: ['Point of View', 'Figurative Language', 'Comparing Texts'] },
      { unit: 'Writing', lessons: ['Persuasive Writing', 'Narrative Essays', 'Research Papers'] },
      { unit: 'Grammar', lessons: ['Verb Tenses', 'Prepositions', 'Comma Rules'] },
      { unit: 'Vocabulary', lessons: ['Greek and Latin Roots', 'Context Clues', 'Academic Vocabulary'] }
    ],
    Science: [
      { unit: 'Matter', lessons: ['Properties of Matter', 'Chemical vs Physical Changes', 'Mixtures and Solutions'] },
      { unit: 'Earth Systems', lessons: ['Water Cycle', 'Ocean Currents', 'Atmosphere'] },
      { unit: 'Space Science', lessons: ['Solar System', 'Stars and Galaxies', 'Earth Moon System'] }
    ],
    'Social Studies': [
      { unit: 'Colonial America', lessons: ['13 Colonies', 'Colonial Life', 'Road to Revolution'] },
      { unit: 'American Revolution', lessons: ['Causes of the Revolution', 'Key Battles', 'Declaration of Independence'] },
      { unit: 'New Nation', lessons: ['Constitution', 'Bill of Rights', 'Westward Expansion'] }
    ]
  },
  6: {
    Math: [
      { unit: 'Ratios and Proportions', lessons: ['Understanding Ratios', 'Unit Rates', 'Proportional Relationships'] },
      { unit: 'Integers', lessons: ['Positive and Negative Numbers', 'Adding Integers', 'Subtracting Integers'] },
      { unit: 'Expressions and Equations', lessons: ['Writing Expressions', 'Solving One-Step Equations', 'Inequalities'] },
      { unit: 'Statistics', lessons: ['Mean Median and Mode', 'Data Displays', 'Measures of Variability'] }
    ],
    'Language Arts': [
      { unit: 'Literary Analysis', lessons: ['Analyzing Characters', 'Plot Structure', 'Author Purpose'] },
      { unit: 'Argumentative Writing', lessons: ['Claims and Evidence', 'Counterarguments', 'Persuasive Techniques'] },
      { unit: 'Research', lessons: ['Evaluating Sources', 'Note-Taking Strategies', 'MLA Format Basics'] },
      { unit: 'Speaking and Listening', lessons: ['Debate Skills', 'Group Discussions', 'Presentations'] }
    ],
    Science: [
      { unit: 'Cells', lessons: ['Cell Structure', 'Plant vs Animal Cells', 'Cell Functions'] },
      { unit: 'Body Systems', lessons: ['Digestive System', 'Circulatory System', 'Respiratory System'] },
      { unit: 'Ecology', lessons: ['Biomes', 'Ecosystems', 'Human Impact on Environment'] }
    ],
    'Social Studies': [
      { unit: 'Ancient Civilizations', lessons: ['Mesopotamia', 'Ancient Egypt', 'Ancient Greece'] },
      { unit: 'World Geography', lessons: ['Maps and Globes', 'Climate Zones', 'Cultural Geography'] },
      { unit: 'Ancient Rome', lessons: ['Roman Republic', 'Roman Empire', 'Fall of Rome'] }
    ]
  },
  7: {
    Math: [
      { unit: 'Proportional Relationships', lessons: ['Constant of Proportionality', 'Proportional Graphs', 'Scale Drawings'] },
      { unit: 'Operations with Rational Numbers', lessons: ['Multiplying and Dividing Integers', 'Operations with Fractions', 'Rational Number Word Problems'] },
      { unit: 'Geometry', lessons: ['Angles', 'Area of Circles', 'Surface Area and Volume'] },
      { unit: 'Probability and Statistics', lessons: ['Probability', 'Sampling', 'Comparing Populations'] }
    ],
    'Language Arts': [
      { unit: 'Literature', lessons: ['Short Stories', 'Poetry Analysis', 'Drama and Plays'] },
      { unit: 'Writing', lessons: ['Narrative Writing', 'Expository Writing', 'Argumentative Essays'] },
      { unit: 'Grammar', lessons: ['Phrases and Clauses', 'Active vs Passive Voice', 'Misplaced Modifiers'] },
      { unit: 'Vocabulary', lessons: ['Word Origins', 'Connotation vs Denotation', 'Academic Language'] }
    ],
    Science: [
      { unit: 'Life Science', lessons: ['Genetics Basics', 'DNA and Heredity', 'Natural Selection'] },
      { unit: 'Human Body', lessons: ['Nervous System', 'Skeletal and Muscular Systems', 'Immune System'] },
      { unit: 'Ecology', lessons: ['Population Dynamics', 'Symbiotic Relationships', 'Conservation'] }
    ],
    'Social Studies': [
      { unit: 'Medieval World', lessons: ['Middle Ages in Europe', 'Islamic Golden Age', 'Asian Civilizations'] },
      { unit: 'Renaissance and Reformation', lessons: ['Renaissance Art and Ideas', 'Protestant Reformation', 'Age of Exploration'] },
      { unit: 'Civics', lessons: ['Rights and Responsibilities', 'Local and State Government', 'Civic Participation'] }
    ]
  },
  8: {
    Math: [
      { unit: 'Linear Equations', lessons: ['Solving Multi-Step Equations', 'Slope', 'Graphing Linear Equations'] },
      { unit: 'Systems of Equations', lessons: ['Solving by Graphing', 'Solving by Substitution', 'Real-World Systems'] },
      { unit: 'Functions', lessons: ['Understanding Functions', 'Linear vs Nonlinear', 'Function Tables'] },
      { unit: 'Geometry', lessons: ['Pythagorean Theorem', 'Transformations', 'Volume of Cylinders Cones and Spheres'] }
    ],
    'Language Arts': [
      { unit: 'Critical Reading', lessons: ['Analyzing Arguments', 'Evaluating Evidence', 'Identifying Bias'] },
      { unit: 'Research Writing', lessons: ['Thesis Statements', 'Research Methods', 'Citations and Bibliography'] },
      { unit: 'Literary Criticism', lessons: ['Historical Context', 'Literary Movements', 'Comparative Analysis'] },
      { unit: 'Communication', lessons: ['Formal vs Informal Writing', 'Public Speaking', 'Digital Literacy'] }
    ],
    Science: [
      { unit: 'Physical Science', lessons: ['Atomic Structure', 'Elements and Compounds', 'Chemical Reactions Basics'] },
      { unit: 'Physics Basics', lessons: ['Forces and Motion', 'Energy and Work', 'Waves and Sound'] },
      { unit: 'Earth and Space', lessons: ['Plate Tectonics', 'Earthquakes and Volcanoes', 'Climate Change'] }
    ],
    'Social Studies': [
      { unit: 'US Constitution', lessons: ['Creating the Constitution', 'Three Branches of Government', 'Amendments'] },
      { unit: 'Civil War Era', lessons: ['Causes of the Civil War', 'Key Battles and Leaders', 'Reconstruction'] },
      { unit: 'Industrialization', lessons: ['Industrial Revolution', 'Immigration', 'Progressive Era'] }
    ]
  },
  9: {
    Math: [
      { unit: 'Foundations of Algebra', lessons: ['Variables and Expressions', 'Order of Operations', 'Properties of Real Numbers'] },
      { unit: 'Linear Equations and Inequalities', lessons: ['Solving Linear Equations', 'Graphing Linear Inequalities', 'Systems of Linear Equations'] },
      { unit: 'Polynomials', lessons: ['Adding and Subtracting Polynomials', 'Multiplying Polynomials', 'Factoring'] },
      { unit: 'Quadratic Functions', lessons: ['Graphing Quadratics', 'Quadratic Formula', 'Applications of Quadratics'] }
    ],
    'Language Arts': [
      { unit: 'Literature Survey', lessons: ['The Short Story', 'The Novel', 'Poetry Forms'] },
      { unit: 'Analytical Writing', lessons: ['Literary Analysis Essay', 'Compare and Contrast', 'Rhetorical Analysis'] },
      { unit: 'Grammar and Style', lessons: ['Sentence Variety', 'Parallel Structure', 'Tone and Voice'] },
      { unit: 'Rhetoric', lessons: ['Ethos Pathos Logos', 'Persuasive Techniques', 'Evaluating Arguments'] }
    ],
    Science: [
      { unit: 'Cell Biology', lessons: ['Cell Structure and Function', 'Cell Division', 'Cellular Respiration'] },
      { unit: 'Genetics', lessons: ['Mendel and Heredity', 'DNA Structure', 'Genetic Mutations'] },
      { unit: 'Evolution', lessons: ['Evidence for Evolution', 'Natural Selection', 'Speciation'] },
      { unit: 'Ecology', lessons: ['Ecosystems and Biomes', 'Population Ecology', 'Human Impact'] }
    ],
    'Social Studies': [
      { unit: 'Ancient World', lessons: ['Early Civilizations', 'Classical Greece and Rome', 'Rise of Religions'] },
      { unit: 'Medieval to Early Modern', lessons: ['Byzantine Empire', 'Crusades', 'Renaissance'] },
      { unit: 'Age of Revolution', lessons: ['Enlightenment', 'French Revolution', 'Industrial Revolution'] },
      { unit: 'Modern World', lessons: ['World War I', 'World War II', 'Cold War'] }
    ]
  },
  10: {
    Math: [
      { unit: 'Foundations of Geometry', lessons: ['Points Lines and Planes', 'Angles and Angle Relationships', 'Parallel Lines'] },
      { unit: 'Triangles', lessons: ['Triangle Properties', 'Congruent Triangles', 'Similar Triangles'] },
      { unit: 'Circles', lessons: ['Circle Properties', 'Arc Length and Sector Area', 'Inscribed Angles'] },
      { unit: 'Area Volume and Transformations', lessons: ['Area of Polygons', 'Volume of Solids', 'Geometric Transformations'] }
    ],
    'Language Arts': [
      { unit: 'World Literature', lessons: ['Ancient and Classical Literature', 'Medieval and Renaissance Works', 'Modern World Literature'] },
      { unit: 'Research and Rhetoric', lessons: ['Advanced Research Methods', 'Argumentative Essays', 'Synthesis Writing'] },
      { unit: 'Critical Analysis', lessons: ['Literary Theory', 'Analyzing Rhetoric', 'Media Literacy'] },
      { unit: 'Creative Writing', lessons: ['Short Story Writing', 'Poetry Composition', 'Personal Narrative'] }
    ],
    Science: [
      { unit: 'Atomic Structure', lessons: ['Atoms and Elements', 'Periodic Table', 'Electron Configuration'] },
      { unit: 'Chemical Bonding', lessons: ['Ionic Bonds', 'Covalent Bonds', 'Metallic Bonds'] },
      { unit: 'Chemical Reactions', lessons: ['Balancing Equations', 'Types of Reactions', 'Stoichiometry'] },
      { unit: 'Solutions and Acids', lessons: ['Solutions and Solubility', 'Acids and Bases', 'pH Scale'] }
    ],
    'Social Studies': [
      { unit: 'Colonial and Revolutionary Era', lessons: ['Colonial Society', 'American Revolution', 'Creating a New Nation'] },
      { unit: 'Growth of the Nation', lessons: ['Westward Expansion', 'Jacksonian Democracy', 'Manifest Destiny'] },
      { unit: 'Civil War and Reconstruction', lessons: ['Slavery and Abolition', 'Civil War', 'Reconstruction Era'] },
      { unit: 'Modern America', lessons: ['World Wars', 'Civil Rights Movement', 'Contemporary Issues'] }
    ]
  },
  11: {
    Math: [
      { unit: 'Polynomial Functions', lessons: ['Polynomial Operations', 'Factoring Polynomials', 'Polynomial Division'] },
      { unit: 'Rational and Radical Functions', lessons: ['Rational Expressions', 'Radical Equations', 'Complex Numbers'] },
      { unit: 'Exponential and Logarithmic', lessons: ['Exponential Functions', 'Logarithmic Functions', 'Exponential Growth and Decay'] },
      { unit: 'Sequences and Series', lessons: ['Arithmetic Sequences', 'Geometric Sequences', 'Series and Summation'] }
    ],
    'Language Arts': [
      { unit: 'American Literature', lessons: ['Early American Literature', 'Transcendentalism', 'American Realism'] },
      { unit: 'Modern American Literature', lessons: ['Harlem Renaissance', 'Modernism', 'Contemporary Literature'] },
      { unit: 'College-Prep Writing', lessons: ['College Application Essays', 'Analytical Writing', 'Advanced Research Papers'] },
      { unit: 'SAT/ACT Prep', lessons: ['Reading Comprehension Strategies', 'Grammar and Usage', 'Essay Writing Under Time'] }
    ],
    Science: [
      { unit: 'Mechanics', lessons: ['Kinematics', 'Newton Laws of Motion', 'Work Energy and Power'] },
      { unit: 'Waves and Sound', lessons: ['Wave Properties', 'Sound Waves', 'Light and Optics'] },
      { unit: 'Electricity', lessons: ['Electric Charge', 'Circuits', 'Magnetism'] },
      { unit: 'Modern Physics', lessons: ['Nuclear Physics', 'Quantum Mechanics Intro', 'Relativity Intro'] }
    ],
    'Social Studies': [
      { unit: 'US Government', lessons: ['Constitution and Federalism', 'Congress', 'The Presidency and Courts'] },
      { unit: 'Civil Liberties', lessons: ['Bill of Rights', 'Due Process', 'Equal Protection'] },
      { unit: 'Economics', lessons: ['Supply and Demand', 'Market Structures', 'Monetary and Fiscal Policy'] },
      { unit: 'Personal Finance', lessons: ['Budgeting', 'Banking and Credit', 'Investing Basics'] }
    ]
  },
  12: {
    Math: [
      { unit: 'Functions and Graphs', lessons: ['Function Analysis', 'Transformations of Functions', 'Inverse Functions'] },
      { unit: 'Trigonometry', lessons: ['Trigonometric Functions', 'Trigonometric Identities', 'Applications of Trigonometry'] },
      { unit: 'Limits and Continuity', lessons: ['Introduction to Limits', 'Evaluating Limits', 'Continuity'] },
      { unit: 'Introduction to Calculus', lessons: ['Derivatives Concept', 'Basic Derivative Rules', 'Applications of Derivatives'] }
    ],
    'Language Arts': [
      { unit: 'British Literature', lessons: ['Anglo-Saxon and Medieval', 'Shakespeare', 'Romantic and Victorian Era'] },
      { unit: 'Modern British Literature', lessons: ['Modernist Writers', 'Post-Colonial Literature', 'Contemporary British Writers'] },
      { unit: 'College Writing', lessons: ['Advanced Composition', 'Academic Research', 'Professional Writing'] },
      { unit: 'Senior Capstone', lessons: ['Senior Research Project', 'Presentation Skills', 'Portfolio Development'] }
    ],
    Science: [
      { unit: 'Geology', lessons: ['Minerals and Rocks', 'Plate Tectonics', 'Geologic Time'] },
      { unit: 'Oceanography', lessons: ['Ocean Floor', 'Ocean Currents', 'Marine Ecosystems'] },
      { unit: 'Meteorology', lessons: ['Atmosphere', 'Weather Systems', 'Climate Patterns'] },
      { unit: 'Astronomy', lessons: ['Stars and Stellar Evolution', 'Galaxies', 'Cosmology'] }
    ],
    'Social Studies': [
      { unit: 'Global Issues', lessons: ['Globalization', 'International Organizations', 'Human Rights'] },
      { unit: 'Geopolitics', lessons: ['World Powers', 'Regional Conflicts', 'Diplomacy'] },
      { unit: 'Sociology', lessons: ['Culture and Society', 'Social Institutions', 'Social Change'] },
      { unit: 'Current Events', lessons: ['Analyzing News', 'Media Literacy', 'Civic Engagement'] }
    ]
  }
};

// Assignment templates per type
function getAssignments(lessonTitle, unitTitle, grade) {
  const duration = grade <= 5 ? '6-8 min' : grade <= 8 ? '8-12 min' : '10-15 min';
  return [
    { title: lessonTitle + ' Practice', instructions: 'Complete the practice worksheet for ' + lessonTitle + '. Show all your work.', type: 'homework', points: 100 },
    { title: lessonTitle + ' Quiz', instructions: 'Answer all questions about ' + lessonTitle + '. You may use your notes.', type: 'quiz', points: 100 }
  ];
}

// Main seed function
async function seedFullCurriculum() {
  try {
    console.log('=== JNM Home Education Program ===');
    console.log('=== Full K-12 Curriculum Seeder ===');
    console.log('');

    // Create admin user
    const hashedPassword = await bcrypt.hash('admin123', 10);
    const userResult = await pool.query(
      "INSERT INTO users (email, password_hash, first_name, last_name, role) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (email) DO UPDATE SET password_hash = $2 RETURNING id",
      ['admin@jnmhomeschool.com', hashedPassword, 'Admin', 'Parent', 'parent']
    );
    const userId = userResult.rows[0].id;
    console.log('Admin user created');

    let totalCourses = 0, totalUnits = 0, totalLessons = 0, totalAssignments = 0;

    for (const [gradeStr, subjects] of Object.entries(FULL_CURRICULUM)) {
      const grade = parseInt(gradeStr);
      console.log('\nGrade ' + grade + ':');

      for (const [subject, units] of Object.entries(subjects)) {
        const subjectKey = subject === 'Math' ? 'math' : subject === 'Language Arts' ? 'ela' : subject === 'Science' ? 'science' : 'ss';
        const videoBase = KA[subjectKey][grade];

        // Find existing course
        const courseResult = await pool.query(
          'SELECT id FROM courses WHERE grade_level = $1 AND subject = $2 AND course_type = $3 LIMIT 1',
          [grade, subject, 'core']
        );

        let courseId;
        if (courseResult.rows.length > 0) {
          courseId = courseResult.rows[0].id;
        } else {
          const nc = await pool.query(
            'INSERT INTO courses (name, grade_level, subject, course_type, description, created_by) VALUES ($1,$2,$3,$4,$5,$6) RETURNING id',
            [grade <= 8 ? 'Grade ' + grade + ' ' + subject : units[0] ? subject : subject, grade, subject, 'core', 'Grade ' + grade + ' ' + subject, userId]
          );
          courseId = nc.rows[0].id;
        }
        totalCourses++;

        for (let u = 0; u < units.length; u++) {
          const unit = units[u];
          const unitResult = await pool.query(
            'INSERT INTO units (course_id, title, unit_number, description) VALUES ($1,$2,$3,$4) RETURNING id',
            [courseId, unit.unit, u + 1, 'Unit ' + (u + 1) + ': ' + unit.unit]
          );
          totalUnits++;

          for (let l = 0; l < unit.lessons.length; l++) {
            const lessonTitle = unit.lessons[l];
            const lessonResult = await pool.query(
              'INSERT INTO lessons (unit_id, title, lesson_number, video_url, video_title, video_duration) VALUES ($1,$2,$3,$4,$5,$6) RETURNING id',
              [unitResult.rows[0].id, lessonTitle, l + 1, videoBase, lessonTitle + ' Video Lesson', grade <= 5 ? '6-8 min' : '10-15 min']
            );
            totalLessons++;

            const assignments = getAssignments(lessonTitle, unit.unit, grade);
            for (const a of assignments) {
              await pool.query(
                'INSERT INTO assignments (lesson_id, title, instructions, assignment_type, weight_category, point_value, passing_grade, allow_retake, created_by) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
                [lessonResult.rows[0].id, a.title, a.instructions, a.type, a.type, a.points, 70, true, userId]
              );
              totalAssignments++;
            }
          }
        }
        console.log('  ' + subject + ': ' + units.length + ' units');
      }
    }

    // Add unit test for each unit
    console.log('\nAdding unit tests...');
    const allUnits = await pool.query('SELECT u.id, u.title, c.grade_level FROM units u JOIN courses c ON u.course_id = c.id');
    for (const unit of allUnits.rows) {
      const lessons = await pool.query('SELECT id FROM lessons WHERE unit_id = $1 ORDER BY lesson_number DESC LIMIT 1', [unit.id]);
      if (lessons.rows.length > 0) {
        await pool.query(
          'INSERT INTO assignments (lesson_id, title, instructions, assignment_type, weight_category, point_value, passing_grade, allow_retake, created_by) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
          [lessons.rows[0].id, unit.title + ' Unit Test', 'Complete this test covering all material from ' + unit.title + '.', 'test', 'test', 100, 70, true, userId]
        );
        totalAssignments++;
      }
    }

    console.log('\n=================================');
    console.log('CURRICULUM SEEDED SUCCESSFULLY!');
    console.log('=================================');
    console.log('Total Courses: ' + totalCourses);
    console.log('Total Units: ' + totalUnits);
    console.log('Total Lessons: ' + totalLessons);
    console.log('Total Assignments: ' + totalAssignments);
    console.log('\nLogin: admin@jnmhomeschool.com / admin123');

    process.exit(0);
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

seedFullCurriculum();
