/**
 * Simple Node.js test for GigLez Pattern Decoder
 *
 * Run with: node static/js/decoder/test.js
 */

import { decode, parseSubFile, getVersion } from './index.js';

// Test .sub file content (RAW format)
const testSubFile = `Filetype: Flipper SubGhz RAW File
Version: 1
Frequency: 315000000
Preset: FuriHalSubGhzPresetOok650Async
Protocol: RAW
RAW_Data: 2980 -240 520 -980 520 -980 1000 -500 480 -1020 520 -980 1000 -500
`;

async function runTest() {
  console.log('='.repeat(80));
  console.log('GigLez Pattern Decoder - Node.js Test');
  console.log('='.repeat(80));
  console.log();

  // Print version
  const version = await getVersion();
  console.log(`${version.name} v${version.version}`);
  console.log(`Protocols: ${version.protocols}`);
  console.log(`Features:`);
  version.features.forEach(f => console.log(`  - ${f}`));
  console.log();

  console.log('-'.repeat(80));
  console.log('Test 1: Parse .sub file');
  console.log('-'.repeat(80));

  const metadata = parseSubFile(testSubFile);
  console.log('Parsed metadata:');
  console.log(`  Frequency: ${metadata.frequency / 1e6} MHz`);
  console.log(`  Protocol: ${metadata.protocol}`);
  console.log(`  Preset: ${metadata.preset}`);
  console.log(`  Pulses: ${metadata.raw_data.length}`);
  console.log(`  Raw Data: ${metadata.raw_data.join(' ')}`);
  console.log();

  console.log('-'.repeat(80));
  console.log('Test 2: Decode signal');
  console.log('-'.repeat(80));

  const matches = await decode(metadata, { debug: true, minConfidence: 0.3 });

  console.log();
  console.log(`Found ${matches.length} device matches:`);
  console.log();

  if (matches.length === 0) {
    console.log('  ❌ No matches found');
  } else {
    matches.forEach((match, i) => {
      console.log(`  ${i + 1}. ${match.toString()}`);
      console.log(`     Method: ${match.matchMethod}`);
      if (match.matchDetails) {
        console.log(`     Details:`);
        Object.entries(match.matchDetails).forEach(([key, value]) => {
          console.log(`       - ${key}: ${value}`);
        });
      }
      console.log();
    });
  }

  console.log('-'.repeat(80));
  console.log('Test 3: Protocol database query');
  console.log('-'.repeat(80));

  // Import protocol database directly
  const { protocolDb } = await import('./protocol-database.js');

  console.log(`Total protocols: ${protocolDb.getAll().length}`);
  console.log();

  const stats = protocolDb.getStatistics();
  console.log('Categories:');
  Object.entries(stats.byCategory).forEach(([cat, count]) => {
    console.log(`  - ${cat}: ${count} protocols`);
  });
  console.log();

  console.log('Frequency bands:');
  stats.frequencyBands.forEach(freq => {
    console.log(`  - ${freq} MHz`);
  });
  console.log();

  console.log('-'.repeat(80));
  console.log('Test 4: Pulse analysis');
  console.log('-'.repeat(80));

  const { analyzePulseTrain, extractFingerprint } = await import('./pulse-analyzer.js');

  const analysis = analyzePulseTrain(metadata.raw_data);
  console.log('Timing Analysis:');
  console.log(`  Short Pulse: ${analysis.shortPulse.toFixed(1)} μs`);
  console.log(`  Long Pulse: ${analysis.longPulse.toFixed(1)} μs`);
  console.log(`  Bit Pattern: ${analysis.bitPattern}`);
  console.log(`  Bit Count: ${analysis.bitCount}`);
  console.log();

  const { extractFingerprint: fpExtract } = await import('./fingerprint.js');
  const fingerprint = fpExtract(metadata.raw_data);
  console.log('Statistical Fingerprint:');
  console.log(`  ${fingerprint.toString()}`);
  console.log(`  Duty Cycle: ${(fingerprint.dutyCycle * 100).toFixed(1)}%`);
  console.log();

  console.log('='.repeat(80));
  console.log('✅ All tests completed!');
  console.log('='.repeat(80));
}

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