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

import { AgentOrchestrator } from './src/core/orchestrator.js';

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

console.log('\n── Orchestrator Fix Skill ──');

const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-fix-skill-'));
fs.mkdirSync(path.join(workDir, '.vl-code'), { recursive: true });

let compileCalls = 0;

const toolRegistry = {
  _skillFilter: null,
  async execute(name) {
    if (name !== 'VLCompile') throw new Error(`Unexpected tool call: ${name}`);
    compileCalls++;
    return {
      result: JSON.stringify({ success: true, errCount: 0, warningCount: 0 }),
      error: null,
    };
  },
  getToolSchemas() { return []; },
};

const contextManager = {
  messages: [],
  turnCount: 0,
  addUserMessage(blocks) { this.messages.push({ role: 'user', content: blocks }); },
  getMessages() { return this.messages; },
};

const promptAssembler = {
  buildInitialReminders() { return []; },
  buildSystemPrompt() { return ''; },
};

const projectContext = {
  isVLProject() { return true; },
  getAllFiles() { return []; },
  getSummary() { return { projectName: path.basename(workDir) }; },
};

try {
  const orchestrator = new AgentOrchestrator({
    config: { workDir, model: 'test-model' },
    toolRegistry,
    contextManager,
    promptAssembler,
    cli: {},
    projectContext,
  });

  const skillNames = orchestrator.getSkills().map(skill => skill.name);
  assert(skillNames.includes('fix'), '/fix alias should be registered as a skill');
  assert(skillNames.includes('compile-fix'), '/compile-fix should remain available');

  let done = false;
  const result = await orchestrator.executeSkill('fix', undefined, {
    onText() {},
    onToolResult() {},
    onPlanMode() {},
    onDone() { done = true; },
  });

  assert(result?.success === true, '/fix alias should use the compile-fix loop');
  assert(compileCalls === 1, '/fix alias should compile the project once when there are no errors');
  assert(done === true, '/fix alias should invoke onDone');

  const intent = orchestrator.detectWorkflowIntent('请修复这个编译错误');
  assert(intent?.type === 'repair', 'compile-error phrasing should route to repair intent, not VLAdjust');

  console.log('PASS test-orchestrator-fix-skill.js');
} finally {
  fs.rmSync(workDir, { recursive: true, force: true });
}
