const mongoose = require('mongoose'); const path = require('path'); require('dotenv').config({ path: path.join(__dirname, '../.env') }); const LawSection = require('../src/models/LawSection'); const { LEGAL_PLAYBOOK } = require('../src/config/legalPlaybook'); async function seedDatabase() { const uri = process.env.MONGODB_URI; if (!uri) { console.error('โŒ MONGODB_URI not found in environment variables.'); process.exit(1); } console.log('๐Ÿ”Œ Connecting to MongoDB for seeding...'); let connected = false; try { await mongoose.connect(uri, { serverSelectionTimeoutMS: 4000 }); console.log('โœ… Connected successfully to Atlas!'); connected = true; } catch (err) { console.warn(`โš ๏ธ Primary MongoDB connection failed: ${err.message}`); console.log('๐Ÿ”Œ Attempting auto-fallback to local MongoDB on port 27017...'); try { await mongoose.connect('mongodb://127.0.0.1:27017/lexguard', { serverSelectionTimeoutMS: 4000 }); console.log('โœ… Connected successfully to Local Fallback MongoDB!'); connected = true; } catch (fallbackErr) { console.error('โŒ Both Atlas and Local MongoDB connections failed. Exiting.', fallbackErr); process.exit(1); } } try { // 1. Clean existing sections console.log('๐Ÿงน Clearing existing LawSection documents...'); const deleteRes = await LawSection.deleteMany({}); console.log(`๐Ÿงน Done! Removed ${deleteRes.deletedCount} items.`); // 2. Build insertion list from LEGAL_PLAYBOOK console.log('๐Ÿ“ฆ Processing legal sections from Playbook...'); const insertList = []; for (const [clauseType, data] of Object.entries(LEGAL_PLAYBOOK)) { if (data && Array.isArray(data.guidelines)) { for (const g of data.guidelines) { // Flatten keywords including clauseType itself const extraKeywords = [ clauseType, g.sectionNumber.toLowerCase(), g.actName.toLowerCase(), ]; const uniqueKeywords = Array.from(new Set([ ...extraKeywords, ...(g.keywords || []), ])); insertList.push({ actKey: g.actKey, actName: g.actName, sectionNumber: g.sectionNumber, title: g.title, content: g.landmark_case ? `${g.content} Landmark Case: ${g.landmark_case}` : g.content, keywords: uniqueKeywords, referenceUrl: g.referenceUrl, }); } } } // 3. Bulk insert to database console.log(`๐Ÿ’พ Inserting ${insertList.length} legal records...`); const result = await LawSection.insertMany(insertList); console.log(`๐ŸŽ‰ Seeding complete! Inserted ${result.length} legal sections into MONGODB.`); } catch (err) { console.error('โŒ Seeding failed with error:', err); } finally { await mongoose.disconnect(); console.log('๐Ÿ”Œ Disconnected from MongoDB.'); } } seedDatabase();