const { generateNodes, analyzeNode, calculateRiskScore } = require('./hazop-ai-service');

// Simple manual test for generateNodes function
async function testGenerateNodes() {
  console.log('Testing generateNodes function...\n');
  
  const testInput = {
    processDescription: 'Crude oil distillation unit with atmospheric and vacuum columns',
    materials: 'Crude oil, naphtha, diesel, residue',
    operatingPressure: '1-5 bar',
    operatingTemperature: '350-400°C',
    processType: 'oil-gas'
  };
  
  try {
    console.log('Input:', JSON.stringify(testInput, null, 2));
    console.log('\nGenerating nodes...');
    
    const nodes = await generateNodes(testInput);
    
    console.log('\n✓ Success! Generated', nodes.length, 'nodes');
    console.log('\nNodes:');
    nodes.forEach((node, index) => {
      console.log(`\n${index + 1}. ${node.nodeNumber}: ${node.description}`);
      console.log(`   Design Intent: ${node.designIntent}`);
      console.log(`   Parameters: ${node.parameters.join(', ')}`);
      console.log(`   Findings: ${node.findings.length}`);
    });
    
    // Validate structure
    console.log('\n--- Validation ---');
    console.log('✓ Node count:', nodes.length, '(expected 4-7)');
    console.log('✓ All nodes have nodeNumber:', nodes.every(n => n.nodeNumber));
    console.log('✓ All nodes have description:', nodes.every(n => n.description));
    console.log('✓ All nodes have designIntent:', nodes.every(n => n.designIntent));
    console.log('✓ All nodes have parameters array:', nodes.every(n => Array.isArray(n.parameters) && n.parameters.length > 0));
    console.log('✓ All nodes have findings array:', nodes.every(n => Array.isArray(n.findings)));
    
  } catch (error) {
    console.error('\n✗ Error:', error.message);
    console.error('Stack:', error.stack);
  }
}

// Test for calculateRiskScore function
function testCalculateRiskScore() {
  console.log('\n\nTesting calculateRiskScore function...\n');
  
  const testCases = [
    { likelihood: 1, severity: 1, expectedScore: 1, expectedLevel: 'Low' },
    { likelihood: 2, severity: 3, expectedScore: 6, expectedLevel: 'Medium' },
    { likelihood: 3, severity: 4, expectedScore: 12, expectedLevel: 'High' },
    { likelihood: 5, severity: 5, expectedScore: 25, expectedLevel: 'Critical' },
    { likelihood: 2, severity: 2, expectedScore: 4, expectedLevel: 'Low' },
    { likelihood: 3, severity: 3, expectedScore: 9, expectedLevel: 'Medium' },
    { likelihood: 4, severity: 3, expectedScore: 12, expectedLevel: 'High' },
    { likelihood: 3, severity: 5, expectedScore: 15, expectedLevel: 'Critical' }
  ];
  
  let passed = 0;
  let failed = 0;
  
  testCases.forEach((testCase, index) => {
    const result = calculateRiskScore(testCase.likelihood, testCase.severity);
    const scoreMatch = result.score === testCase.expectedScore;
    const levelMatch = result.level === testCase.expectedLevel;
    
    if (scoreMatch && levelMatch) {
      console.log(`✓ Test ${index + 1}: L=${testCase.likelihood}, S=${testCase.severity} → Score=${result.score}, Level=${result.level}`);
      passed++;
    } else {
      console.log(`✗ Test ${index + 1}: L=${testCase.likelihood}, S=${testCase.severity}`);
      console.log(`  Expected: Score=${testCase.expectedScore}, Level=${testCase.expectedLevel}`);
      console.log(`  Got: Score=${result.score}, Level=${result.level}`);
      failed++;
    }
  });
  
  console.log(`\n--- Risk Score Calculation Results ---`);
  console.log(`Passed: ${passed}/${testCases.length}`);
  console.log(`Failed: ${failed}/${testCases.length}`);
}

// Test for analyzeNode function
async function testAnalyzeNode() {
  console.log('\n\nTesting analyzeNode function...\n');
  
  const testNode = {
    nodeNumber: 'N-01',
    description: 'Crude oil feed system',
    designIntent: 'Transfer crude oil from storage to distillation column at controlled rate',
    parameters: ['Flow', 'Pressure', 'Temperature'],
    findings: []
  };
  
  const testInput = {
    node: testNode,
    processDescription: 'Crude oil distillation unit with atmospheric and vacuum columns',
    materials: 'Crude oil, naphtha, diesel, residue',
    operatingConditions: 'Pressure: 1-5 bar, Temperature: 350-400°C'
  };
  
  try {
    console.log('Node:', testNode.nodeNumber, '-', testNode.description);
    console.log('Parameters:', testNode.parameters.join(', '));
    console.log('\nAnalyzing node...');
    
    const findings = await analyzeNode(testInput);
    
    console.log('\n✓ Success! Generated', findings.length, 'findings');
    
    // Validate guideword coverage
    const guidewords = findings.map(f => f.guideword);
    const uniqueGuidewords = [...new Set(guidewords)];
    const requiredGuidewords = ['No', 'More', 'Less', 'As Well As', 'Reverse', 'Other Than'];
    
    console.log('\n--- Guideword Coverage ---');
    requiredGuidewords.forEach(gw => {
      const covered = uniqueGuidewords.includes(gw);
      console.log(`${covered ? '✓' : '✗'} ${gw}: ${covered ? 'Covered' : 'MISSING'}`);
    });
    
    // Display findings summary
    console.log('\n--- Findings Summary ---');
    findings.forEach((finding, index) => {
      console.log(`\n${index + 1}. ${finding.findingRef}: ${finding.deviation}`);
      console.log(`   Parameter: ${finding.parameter}`);
      console.log(`   Guideword: ${finding.guideword}`);
      console.log(`   Causes: ${finding.causes.length} items`);
      console.log(`   Consequences: ${finding.consequences.length} items`);
      console.log(`   Safeguards: ${finding.safeguards.length} items`);
      console.log(`   Recommendations: ${finding.recommendations.length} items`);
      console.log(`   Risk: L=${finding.likelihood}, S=${finding.severity}, Score=${finding.riskScore}, Level=${finding.riskLevel}`);
    });
    
    // Validate structure
    console.log('\n--- Validation ---');
    console.log('✓ Finding count:', findings.length);
    console.log('✓ All findings have findingRef:', findings.every(f => f.findingRef));
    console.log('✓ All findings have parameter:', findings.every(f => f.parameter));
    console.log('✓ All findings have guideword:', findings.every(f => f.guideword));
    console.log('✓ All findings have deviation:', findings.every(f => f.deviation));
    console.log('✓ All findings have causes array:', findings.every(f => Array.isArray(f.causes)));
    console.log('✓ All findings have consequences array:', findings.every(f => Array.isArray(f.consequences)));
    console.log('✓ All findings have safeguards array:', findings.every(f => Array.isArray(f.safeguards)));
    console.log('✓ All findings have recommendations array:', findings.every(f => Array.isArray(f.recommendations)));
    console.log('✓ All findings have valid likelihood (1-5):', findings.every(f => f.likelihood >= 1 && f.likelihood <= 5));
    console.log('✓ All findings have valid severity (1-5):', findings.every(f => f.severity >= 1 && f.severity <= 5));
    console.log('✓ All findings have riskScore:', findings.every(f => typeof f.riskScore === 'number'));
    console.log('✓ All findings have riskLevel:', findings.every(f => ['Low', 'Medium', 'High', 'Critical'].includes(f.riskLevel)));
    console.log('✓ All 6 guidewords covered:', uniqueGuidewords.length === 6);
    
  } catch (error) {
    console.error('\n✗ Error:', error.message);
    console.error('Stack:', error.stack);
  }
}

// Run tests if executed directly
if (require.main === module) {
  (async () => {
    await testGenerateNodes();
    testCalculateRiskScore();
    await testAnalyzeNode();
  })();
}

module.exports = { testGenerateNodes, testCalculateRiskScore, testAnalyzeNode };
