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

import { createVLCompileTool } from './src/tools/vl-compile.js';

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

console.log('\n── VLCompile Warning Handling ──');

const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-compile-tool-'));
const originalFetch = global.fetch;

global.fetch = async () => ({
  async text() {
    return [
      'event: status',
      'data: {"status":"success"}',
      '',
      'event: result',
      'data: {"data":{"gid":1653,"errList":[{"level":"warning","message":"deprecated"}],"apps":{"frontends":{"Apps/TeacherApp.vx":{"previewUrl":"https://example.test/app"}}}}}',
      '',
    ].join('\n');
  },
});

try {
  const tool = createVLCompileTool({ workDir, port: 4002 });
  const result = JSON.parse(await tool.execute({}));
  assert(result.success === true, 'warning-only compile should be treated as success');
  assert(result.errCount === 0, 'warning-only compile should have zero hard errors');
  assert(result.warningCount === 1, 'warning count should be preserved');
  assert(result.previewUrls['Apps/TeacherApp.vx'] === 'https://example.test/app', 'preview URL should be preserved on warning-only compile');
  console.log('PASS test-vl-compile-warnings.js');
} finally {
  global.fetch = originalFetch;
}
