import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
import { processMeldFile } from '../src/meld';

describe('meld', () => {
  const testDir = join(__dirname, 'fixtures');
  let inputFile: string;

  beforeEach(() => {
    inputFile = join(testDir, 'input.md');
  });

  afterEach(() => {
    try {
      unlinkSync(inputFile);
    } catch (e) {
      // Ignore if file doesn't exist
    }
  });

  it('processes markdown imports correctly', async () => {
    writeFileSync(inputFile, `
# Test Document

@import[test.md # Section One]
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.content).toContain('This is section one content');
    expect(result.errors).toHaveLength(0);
  }, 1000);

  it('processes code imports correctly', async () => {
    writeFileSync(inputFile, `
# Test Document

@import[test.ts # testFunction1]
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.content).toContain('function testFunction1()');
    expect(result.errors).toHaveLength(0);
  }, 1000);

  it('processes imports with heading level and text overrides', async () => {
    writeFileSync(inputFile, `
# Test Document

@import[test.md # Section One] as ### "Custom Title"
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.content).toContain('### Custom Title');
    expect(result.content).toContain('This is section one content');
    expect(result.errors).toHaveLength(0);
  }, 1000);

  it('handles multiple imports on the same line', async () => {
    writeFileSync(inputFile, `
# Test Document

Here are two imports: @import[test.md # Section One] and @import[test.ts # testFunction1]
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.content).toContain('This is section one content');
    expect(result.content).toContain('function testFunction1()');
    expect(result.errors).toHaveLength(0);
  }, 1000);

  it('handles errors gracefully', async () => {
    writeFileSync(inputFile, `
# Test Document

@import[nonexistent.md # Section]
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.errors).toHaveLength(1);
    expect(result.errors[0]).toContain('Error processing import directive');
  }, 1000);

  it('processes command placeholders', async () => {
    writeFileSync(inputFile, `
# Test Document

@cmd[echo "hello world"]
    `);

    const result = await processMeldFile({
      inputPath: inputFile,
      workspacePath: testDir
    });

    expect(result.content).toContain('hello world');
    expect(result.errors).toHaveLength(0);
  }, 1000);
}); 