#!/usr/bin/env node
/**
 * Test Memory Service Connection
 * 
 * Verifies NocoDB connection and tests CRUD operations
 */

const MemoryService = require('./memory-service');

async function test() {
  console.log('=== Testing Memory Service Connection ===\n');

  // Initialize service with working configuration
  const memory = new MemoryService({
    nocodbUrl: 'http://192.168.25.5:8080',
    nocodbToken: 'owuYNodz0RcnDtUqnj5DK4Qeyp3ASQkDYkrdfGtw', // From vault
    baseId: 'pedwxnsn51vxdq2',
    tableId: 'mx149yctebfwvys'
  });

  // Test 1: Connection
  console.log('1. Testing connection...');
  const conn = await memory.testConnection();
  console.log(conn.success ? '✅ Connected' : '❌ Failed:', conn.message);
  console.log('   Records:', conn.recordCount);

  if (!conn.success) {
    console.log('\nCannot proceed without connection.');
    process.exit(1);
  }

  // Test 2: Store a correction
  console.log('\n2. Testing correction storage...');
  try {
    const correction = await memory.storeCorrection({
      pattern: '\\d+\\s*(%|percent)',
      severity: 'auto-correct',
      message: 'Quantitative claim requires evidence',
      suggestion: 'Add source or measurement',
      blocking: true,
      autoDetected: true,
      context: 'test'
    });
    console.log('✅ Correction stored:', correction.id);
  } catch (err) {
    console.log('❌ Failed:', err.message);
  }

  // Test 3: Load corrections
  console.log('\n3. Testing correction loading...');
  try {
    const corrections = await memory.loadCorrections();
    console.log(`✅ Loaded ${corrections.length} corrections`);
    corrections.forEach(c => console.log(`   - ${c.id}: ${c.message.substring(0, 50)}...`));
  } catch (err) {
    console.log('❌ Failed:', err.message);
  }

  // Test 4: Store preference
  console.log('\n4. Testing preference storage...');
  try {
    const pref = await memory.storePreference({
      category: 'communication',
      key: 'format',
      value: 'concise',
      importance: 9,
      confidence: 1.0,
      tags: ['format', 'style']
    });
    console.log('✅ Preference stored:', pref.id);
  } catch (err) {
    console.log('❌ Failed:', err.message);
  }

  // Test 5: Get preferences
  console.log('\n5. Testing preference loading...');
  try {
    const prefs = await memory.getPreferences('communication', 5);
    console.log(`✅ Loaded ${prefs.length} preferences`);
  } catch (err) {
    console.log('❌ Failed:', err.message);
  }

  // Test 6: Log validation
  console.log('\n6. Testing validation logging...');
  try {
    await memory.logValidation({
      sessionId: 'test-session',
      inputLength: 100,
      outputLength: 200,
      violationsFound: 1,
      newPatternsDetected: 0,
      correctionsAutoStored: 1,
      processingTimeMs: 50,
      blocked: true,
      workflow: 'test'
    });
    console.log('✅ Validation logged');
  } catch (err) {
    console.log('❌ Failed:', err.message);
  }

  console.log('\n=== Tests Complete ===');
}

test().catch(err => {
  console.error('Test error:', err);
  process.exit(1);
});
