/**
 * @fileoverview Debug markup block parsing
 */

import { describe, expect, it } from 'vitest';
import { OrdoJSLexer } from './lexer.js';
import { OrdoJSParser } from './parser.js';

describe('Debug Markup Parsing', () => {
  it('should trace markup block parsing', () => {
    const source = `
      component TestComponent {
        markup {
          <div>Hello World</div>
        }
      }
    `;

    const lexer = new OrdoJSLexer(source, 'test.ordo');
    const tokens = lexer.tokenize();

    // Create a custom parser with debug logging
    class DebugParser extends (OrdoJSParser as any) {
      parseMarkupBlock() {
        console.log('\n=== Starting parseMarkupBlock ===');
        console.log('Current token position:', this.tokens.current);
        console.log('Current token:', this.tokens.peek());

        this.skipWhitespace();
        const start = this.current();

        this.consume('MARKUP', "Expected 'markup' keyword");
        this.consume('LEFT_BRACE', "Expected '{' after 'markup'");

        const elements = [];
        const textNodes = [];
        const interpolations = [];

        console.log('\n--- Starting markup content parsing loop ---');
        let loopCount = 0;

        // Parse markup content
        while (!this.check('RIGHT_BRACE') && !this.isAtEnd()) {
          loopCount++;
          console.log(`\nLoop iteration ${loopCount}:`);
          console.log('  Position:', this.tokens.current);
          console.log('  Token:', this.tokens.peek());

          this.skipWhitespace();
          if (this.check('RIGHT_BRACE')) {
            console.log('  Found RIGHT_BRACE, breaking');
            break;
          }

          if (loopCount > 10) {
            console.log('  SAFETY BREAK: Too many iterations');
            break;
          }

          try {
            if (this.check('HTML_TAG_OPEN')) {
              console.log('  Parsing HTML element...');
              const element = this.parseHTMLElement();
              elements.push(element);
              console.log('  HTML element parsed, new position:', this.tokens.current);
            } else if (this.check('HTML_TEXT')) {
              console.log('  Parsing text node...');
              textNodes.push(this.parseTextNode());
            } else if (this.check('INTERPOLATION_START')) {
              console.log('  Parsing interpolation...');
              interpolations.push(this.parseInterpolation());
            } else {
              console.log('  Skipping unexpected token:', this.tokens.peek());
              this.advance();
            }
          } catch (error) {
            console.log('  Error in loop:', error.message);
            break;
          }
        }

        console.log('\n--- Finished markup content parsing loop ---');
        console.log('Final position:', this.tokens.current);
        console.log('Final token:', this.tokens.peek());
        console.log('Elements parsed:', elements.length);

        try {
          this.consume('RIGHT_BRACE', "Expected '}' to close markup block");
          console.log('Successfully consumed closing brace');
        } catch (error) {
          console.log('Failed to consume closing brace:', error.message);
          throw error;
        }

        const end = this.previous();

        return {
          type: 'MarkupBlock',
          elements,
          textNodes,
          interpolations,
          range: this.createRange(start.position, end.position),
          children: [...elements, ...textNodes, ...interpolations]
        };
      }
    }

    const parser = new DebugParser(tokens, { allowRecovery: true }, 'test.ordo');

    // Advance to the markup keyword
    tokens.current = 5; // Position at 'markup'

    try {
      const markupBlock = parser.parseMarkupBlock();
      console.log('\nMarkup parsing succeeded!');
      console.log('Elements:', markupBlock.elements.length);
    } catch (error) {
      console.log('\nMarkup parsing failed:', error.message);
      console.log('Final position:', tokens.current);
      console.log('Final token:', tokens.peek());
    }

    expect(true).toBe(true);
  });
});
