#!/usr/bin/env node

/**
 * Load inst_035 (Precedent Database Design) into MongoDB
 * This resolves the startup warning about missing inst_035
 */

// Load environment variables from .env file
require('dotenv').config();

const mongoose = require('mongoose');
const config = require('../src/config/app.config');

const instructionData = {
  id: "inst_035",
  text: "Precedent database stores past deliberations as INFORMATIVE (not binding) precedents. Each entry documents: decision context, moral frameworks in tension, stakeholders consulted, values prioritized/deprioritized, moral remainder, dissenting views, justification, precedent applicability SCOPE (not universal rule), review date. When similar case arises: (1) CrossReferenceValidator identifies relevant precedents, (2) Human reviews for context similarity, (3) Precedent INFORMS new deliberation but doesn't dictate outcome, (4) Document why following or departing from precedent. Precedents are PROVISIONAL - reviewable when context changes, scale shifts, new evidence emerges. Prevent precedent creep into rigid hierarchy.",
  timestamp: "2025-10-12T14:35:00Z",
  quadrant: "OPERATIONAL",
  persistence: "HIGH",
  temporal_scope: "PERMANENT",
  verification_required: "MANDATORY",
  explicitness: 1.0,
  source: "user",
  session_id: "2025-10-12-value-pluralism-implementation",
  parameters: {
    precedent_type: "informative_not_binding",
    precedent_fields: [
      "context",
      "frameworks_in_tension",
      "stakeholders",
      "values_prioritized",
      "values_deprioritized",
      "moral_remainder",
      "dissent",
      "justification",
      "applicability_scope",
      "review_date"
    ],
    precedent_matching: "CrossReferenceValidator identifies similar cases",
    human_review_required: "Context similarity assessment",
    precedent_role: "Informs, doesn't dictate",
    departure_documentation: "Explain why not following precedent",
    provisional_nature: "Reviewable when context/scale/evidence changes",
    prevent: "Precedent creep into universal rules",
    related_component: [
      "PluralisticDeliberationOrchestrator",
      "CrossReferenceValidator"
    ]
  },
  active: true,
  notes: "CORE VALUE PLURALISM IMPLEMENTATION 2025-10-12 - Precedent database design prevents rigid hierarchy while enabling learning from past deliberations. Precedents are PROVISIONAL (Gutmann & Thompson) - decisions aren't final, they're revisable. Key distinction: precedent = 'in similar past case we did X' NOT 'therefore you must do X'. Context matters: scale changes (1000 users → 87 million users = re-deliberate), new evidence (theoretical harm now documented = re-deliberate), changed circumstances = review. Git-like versioning tracks how thinking evolved over time."
};

async function loadInstruction() {
  try {
    console.log('🔌 Connecting to MongoDB...');
    await mongoose.connect(config.mongodb.uri, config.mongodb.options);
    console.log('✅ Connected to MongoDB');

    const db = mongoose.connection.db;
    const collection = db.collection('governanceRules'); // Must match model collection name

    // Check if inst_035 already exists
    const existing = await collection.findOne({ id: 'inst_035' });

    if (existing) {
      console.log('⚠️  inst_035 already exists in database');
      console.log('   Updating with latest version...');

      await collection.updateOne(
        { id: 'inst_035' },
        { $set: instructionData }
      );

      console.log('✅ inst_035 updated successfully');
    } else {
      console.log('📝 Inserting inst_035...');
      await collection.insertOne(instructionData);
      console.log('✅ inst_035 inserted successfully');
    }

    // Verify insertion
    const inserted = await collection.findOne({ id: 'inst_035' });
    console.log('\n📋 Verification:');
    console.log(`   ID: ${inserted.id}`);
    console.log(`   Quadrant: ${inserted.quadrant}`);
    console.log(`   Persistence: ${inserted.persistence}`);
    console.log(`   Text: ${inserted.text.substring(0, 80)}...`);
    console.log(`   Related Components: ${inserted.parameters.related_component.join(', ')}`);

    await mongoose.connection.close();
    console.log('\n✅ Done! MongoDB connection closed.');
    process.exit(0);

  } catch (error) {
    console.error('❌ Error loading instruction:', error);
    await mongoose.connection.close();
    process.exit(1);
  }
}

loadInstruction();
