#!/usr/bin/env node
import assert from 'assert';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { WebServer } from './src/server/server.js';

function createTempProject() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-tool-state-'));
  fs.mkdirSync(path.join(dir, '.vl-code'), { recursive: true });
  fs.writeFileSync(path.join(dir, '.vl-code', 'workspace.json'), '{}');
  return dir;
}

async function main() {
  const workDir = createTempProject();
  const projectContext = {
    workDir,
    async load() {},
    async scan() {},
    isVLProject() { return true; },
    getSummary() { return { projectName: path.basename(workDir) }; },
    getAllFiles() { return []; },
  };
  const toolRegistry = {
    clear() {},
    execute: async () => ({}),
    getToolSchemas() { return []; },
  };

  const server = new WebServer({
    config: { workDir, port: 4002 },
    orchestrator: null,
    projectContext,
    contextManager: null,
    toolRegistry,
    symbolIndex: null,
    impactAnalyzer: null,
    autoFix: null,
    localWorkspace: null,
    blueprintContext: null,
  });

  clearInterval(server._sseHeartbeat);
  server.autoExtractMeta = () => {};

  server.config._onWorkflowStart('parallel-codegen');
  assert.equal(server._currentRunState.active, true);
  assert.equal(server._currentRunState.workflowName, 'parallel-codegen');
  assert.deepEqual(server._currentRunState.nodeStatuses, {});

  server.config._onWorkflowNodeStatus('LLM_010_GenMeta', 'running');
  assert.equal(server._currentRunState.nodeStatuses.LLM_010_GenMeta, 'running');

  server.config._onWorkflowDone();
  await new Promise((resolve) => setTimeout(resolve, 0));
  assert.equal(server._currentRunState.active, false);
  assert.equal(server._currentRunState.workflowName, null);
  assert.equal(server._activeExecutor, null);

  server.config._onWorkflowStart('parallel-codegen');
  server.config._onWorkflowError('parallel-codegen', 'boom');
  assert.equal(server._currentRunState.active, false);
  assert.equal(server._currentRunState.workflowName, null);

  fs.rmSync(workDir, { recursive: true, force: true });
  console.log('\n── Tool Workflow State Sync ──');
  console.log('PASS test-tool-workflow-state-sync.js');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
