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

import { analyzeCompileResult, persistLastCompileReport } from './src/server/routes/compile.js';

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

console.log('\n── Compile Report Persistence ──');

const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-compile-report-'));

try {
  const rawResult = {
    code: 0,
    data: {
      gid: 1653,
      errList: [
        { level: 'warning', file: 'Apps/Demo.vx', line: 3, message: 'deprecated prop' },
        { level: 'error', file: 'Apps/Demo.vx', line: 12, message: 'Unexpected token' },
      ],
      appPreviewUrlMap: {
        'Apps/Demo.vx': 'https://example.test/demo',
      },
    },
  };

  const analysis = analyzeCompileResult(rawResult, { action: 'parsePjt' });
  assert(analysis.success === false, 'hard errors should keep compile result unsuccessful');
  assert(analysis.errCount === 1, 'hard error count should exclude warnings');
  assert(analysis.warningCount === 1, 'warning count should be preserved');
  assert(Array.isArray(analysis.errList) && analysis.errList.length === 1, 'errList should only contain hard errors');
  assert(Array.isArray(analysis.warningList) && analysis.warningList.length === 1, 'warningList should only contain warnings');
  assert(analysis.previewUrls['Apps/Demo.vx'] === 'https://example.test/demo', 'preview URLs should be extracted');

  const report = persistLastCompileReport(workDir, rawResult, { action: 'parsePjt' });
  const savedPath = path.join(workDir, '.vl-code', 'last-compile.json');
  const saved = JSON.parse(fs.readFileSync(savedPath, 'utf-8'));

  assert(report.errCount === 1, 'persisted report should keep hard error count');
  assert(saved.warningCount === 1, 'persisted report should keep warning count');
  assert(saved.errList.length === 1, 'persisted errList should only contain hard errors');
  assert(saved.warningList.length === 1, 'persisted warningList should only contain warnings');
  assert(saved.previewUrls['Apps/Demo.vx'] === 'https://example.test/demo', 'persisted preview URLs should be preserved');
  assert(typeof saved.timestamp === 'string' && saved.timestamp.length > 0, 'persisted report should include timestamp');

  console.log('PASS test-compile-report-persistence.js');
} finally {
  fs.rmSync(workDir, { recursive: true, force: true });
}
