import fs from 'fs';
import os from 'os';
import path from 'path';

import { WorkflowExecutor } from './src/vl/workflow-executor.js';

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

console.log('\n── Workflow readFiles Context ──');

const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-workflow-readfiles-'));
fs.mkdirSync(path.join(workDir, 'Apps'), { recursive: true });
fs.writeFileSync(
  path.join(workDir, 'Apps', 'Demo.vx'),
  '// VL_VERSION:3.5\n<App-Demo>\n  <Page-Demo />\n</App-Demo>\n',
  'utf-8'
);

let captured = null;

try {
  const executor = new WorkflowExecutor({ workDir, model: 'test-model' });
  executor.client = {
    messages: {
      async create(params) {
        captured = params;
        return {
          content: [{ type: 'text', text: '{"ok":true}' }],
          usage: {},
          stop_reason: 'end_turn',
          model: 'test-model',
        };
      },
    },
  };

  const adapter = executor._buildLLMAdapter();
  await adapter.call({
    readFiles: ['Apps/Demo.vx'],
    messages: [{ role: 'user', content: 'Regenerate this app entry.' }],
    output_config: { format: { type: 'json_object' } },
  });

  assert(Array.isArray(captured?.messages) && captured.messages.length >= 2, 'readFiles should prepend file context to the LLM messages');
  assert(captured.messages[0].content.includes('<file-context path="Apps/Demo.vx">'), 'prepended file context should include the requested path');
  assert(captured.messages[0].content.includes('// VL_VERSION:3.5'), 'prepended file context should include current file content');
  assert(captured.messages[1].content === 'Regenerate this app entry.', 'original user message should remain after the file context');

  console.log('PASS test-workflow-read-files.js');
} finally {
  fs.rmSync(workDir, { recursive: true, force: true });
}
