const fs = require('fs');

async function runE2EDataTest() {
  console.log('=== STARTING DWG DATA & LINETYPE ACCURACY E2E TEST ===');
  
  const acadrust = await import('./src/viewer2d/acadrust-dwg/acadrust_dwg.js');
  const wasmBuffer = fs.readFileSync('./src/viewer2d/acadrust-dwg/acadrust_dwg_bg.wasm');
  await acadrust.default({ module_or_path: wasmBuffer });
  
  const dwgFile = './dist/samples/C0060202-001-평면및종단면도(1)(대산방향STA.18+492.08-19+411.50).dwg';
  const buf = fs.readFileSync(dwgFile);
  const result = acadrust.parse_dwg(new Uint8Array(buf));
  
  console.log('1. Checking DWG Header & Vars:');
  console.log('   Global LTSCALE:', result.vars?.ltscale);
  
  console.log('\n2. Checking DWG Text Styles Table:');
  const styles = result.tables?.styles || result.tables?.textStyles || [];
  console.log(`   Found ${styles.length} text styles:`);
  for (const st of styles) {
    console.log(`   - Style [${st.name || st.styleName}]: height=${st.height ?? 0}, font=${st.fontFile || st.font || 'default'}`);
  }
  
  console.log('\n3. Checking DWG Linetype Table:');
  const lineTypes = result.tables?.lineTypes || [];
  console.log(`   Found ${lineTypes.length} linetypes in DWG table:`);
  for (const lt of lineTypes) {
    if (lt.name && (lt.name.includes('DICH') || lt.name.includes('L06') || lt.name.includes('L02'))) {
      console.log(`   - Linetype [${lt.name}]: desc="${lt.description}", patternLen=${lt.patternLength}, elements=[${lt.pattern?.join(', ')}]`);
    }
  }

  console.log('\n4. Verifying Complex Linetype Math in Viewer2D with DWG Embedded Data:');
  const { getLinPattern, mergeDwgLinetypePattern } = await import('file:///d:/MYCLAUDE_PROJECT/dwg-dxf-viewer-sample/src/viewer2d/linParser.ts');
  const targetTypes = ['H-DICHL06', 'H-DICHL06R', 'H-DICHL02R', 'H-DICHL01R', 'H-DICHL05'];
  
  const dwgLtMap = new Map();
  for (const lt of lineTypes) {
    if (lt.name && lt.pattern) dwgLtMap.set(lt.name.toUpperCase(), lt);
  }

  for (const name of targetTypes) {
    const dwgLt = dwgLtMap.get(name);
    const pattern = mergeDwgLinetypePattern(name, dwgLt?.pattern || [], dwgLt?.description);
    if (!pattern) {
      console.error(`   [FAIL] Pattern ${name} not found in registry!`);
      continue;
    }
    console.log(`\n   * Pattern [${pattern.name}] (patternLength = ${pattern.patternLength}):`);
    let cumulativeDist = 0;
    for (let i = 0; i < pattern.elements.length; i++) {
      const elem = pattern.elements[i];
      const nextElem = pattern.elements[(i + 1) % pattern.elements.length];
      if (elem.type === 'dash') {
        const dLen = elem.val || 0;
        console.log(`     - [${i}] DASH: len=${dLen} (dist: ${cumulativeDist.toFixed(4)} -> ${(cumulativeDist + dLen).toFixed(4)})`);
        cumulativeDist += dLen;
      } else if (elem.type === 'gap') {
        const gLen = Math.abs(elem.val || 0);
        console.log(`     - [${i}] GAP: len=${gLen} (dist: ${cumulativeDist.toFixed(4)} -> ${(cumulativeDist + gLen).toFixed(4)})`);
        cumulativeDist += gLen;
      } else if (elem.type === 'shape') {
        console.log(`     - [${i}] SHAPE: name=${elem.shapeName}, scale=${elem.scale}, rot=${elem.rotation} at dist=${cumulativeDist.toFixed(4)}`);
      } else if (elem.type === 'text') {
        const textGapLen = (nextElem && nextElem.type === 'gap') ? Math.abs(nextElem.val || 0) : 0;
        const textMidDist = cumulativeDist + textGapLen / 2;
        console.log(`     - [${i}] TEXT: "${elem.text}", scale=${elem.scale}, style=${elem.style}, yOffset=${elem.yOffset}`);
        console.log(`       -> Text Gap Start: ${cumulativeDist.toFixed(4)}, Gap End: ${(cumulativeDist + textGapLen).toFixed(4)}`);
        console.log(`       -> Text EXACT MIDPOINT: ${textMidDist.toFixed(4)} (Midpoint between previous element and next element)`);
      }
    }
  }

  console.log('\n=== E2E DATA ACCURACY TEST COMPLETED SUCCESSFULLY ===');
}

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