#!/usr/bin/env node

/**
 * Test script for Ignite Memory Integration
 * Run with: node test-memory-integration.js
 */

const { MemoryBridge } = require('./ignite/memory/lib/memory-bridge.js');
const SessionManager = require('./ignite/memory/lib/session-manager.js');
const ContextEnricher = require('./ignite/memory/lib/context-enricher.js');

async function testMemoryIntegration() {
  console.log('🧪 Testing Ignite Memory Integration...\n');

  // Initialize memory bridge
  console.log('1️⃣  Initializing Memory Bridge...');
  const memoryBridge = new MemoryBridge({
    workerPort: 37777,
    dataDir: './.ignite/memory'
  });

  const initResult = await memoryBridge.initialize();
  if (!initResult.success) {
    console.error('❌ Failed to initialize memory:', initResult.error);
    return;
  }
  console.log('✅ Memory bridge initialized\n');

  // Test session management
  console.log('2️⃣  Testing Session Management...');
  const sessionManager = new SessionManager(memoryBridge);

  const session = await sessionManager.startSession({
    project: 'test-project',
    phase: 'phase-1',
    agent: 'planner',
    command: 'ignite:plan-phase',
    userPrompt: 'Test planning phase 1'
  });

  console.log(`✅ Session created: ${session.id}\n`);

  // Test observation capture
  console.log('3️⃣  Testing Observation Capture...');
  const observation = await sessionManager.addObservation(session.id, {
    type: 'decision',
    title: 'Test Decision',
    content: 'Decided to use TypeScript for the project',
    concepts: ['TypeScript', 'JavaScript', 'Type Safety'],
    facts: ['TypeScript provides static typing', 'Better IDE support']
  });

  console.log('✅ Observation captured\n');

  // Test context enrichment
  console.log('4️⃣  Testing Context Enrichment...');
  const enricher = new ContextEnricher(memoryBridge);

  const originalPrompt = `
<objective>
Plan the authentication system for the application.
</objective>

<memory_injection_point/>

<instructions>
Create detailed plans for user authentication.
</instructions>
  `;

  const enrichedPrompt = await enricher.enrichPrompt(originalPrompt, {
    project: 'test-project',
    phase: 'phase-1',
    agent: 'planner'
  });

  const hasMemoryContext = enrichedPrompt.includes('<memory_context');
  console.log(`✅ Context ${hasMemoryContext ? 'successfully injected' : 'injection failed'}\n`);

  // Test memory search
  console.log('5️⃣  Testing Memory Search...');
  const searchResults = await memoryBridge.search('TypeScript', {
    project: 'test-project',
    limit: 5
  });

  console.log(`✅ Search returned ${searchResults.results?.length || 0} results\n`);

  // Test similar work finder
  console.log('6️⃣  Testing Similar Work Finder...');
  const similarWork = await memoryBridge.findSimilar('authentication system', {
    limit: 3
  });

  console.log(`✅ Found ${similarWork.results?.length || 0} similar items\n`);

  // Capture agent execution
  console.log('7️⃣  Testing Agent Execution Capture...');
  const agentOutput = `
I've analyzed the requirements and created the following plan:

<observation type="decision" title="Authentication Strategy">
Chose JWT-based authentication for stateless operation and scalability.
Considered session-based auth but rejected due to distributed deployment needs.
</observation>

The plan includes:
1. User registration with email verification
2. JWT token generation and validation
3. Refresh token rotation
4. Rate limiting on auth endpoints
  `;

  const observations = await sessionManager.captureAgentExecution(session.id, {
    agent: 'planner',
    input: 'Plan authentication',
    output: agentOutput,
    files: {
      read: ['requirements.md', 'tech-stack.md'],
      modified: ['PLAN.md']
    }
  });

  console.log(`✅ Captured ${observations.length} observations from agent output\n`);

  // End session with summary
  console.log('8️⃣  Testing Session Closure...');
  const closedSession = await sessionManager.endSession(session.id);
  console.log('✅ Session closed and archived\n');

  // Test project insights
  console.log('9️⃣  Testing Project Insights...');
  const insights = await memoryBridge.getProjectInsights('test-project');
  console.log('✅ Retrieved project insights\n');

  // Summary
  console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  console.log(' 🎉 All Memory Integration Tests Passed!');
  console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  console.log('\nThe Ignite Memory System is ready to use!');
  console.log('\nNext steps:');
  console.log('1. Run "ignite:ui" to open the memory interface');
  console.log('2. Use "ignite:memory-search" to query past work');
  console.log('3. Agents will automatically use memory context');

  process.exit(0);
}

// Run tests
testMemoryIntegration().catch(error => {
  console.error('❌ Test failed:', error);
  process.exit(1);
});