#!/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';
import { createVLGenerateTool } from './src/tools/vl-generate.js';
import { createVLAdjustTool } from './src/tools/vl-adjust.js';
import { createWorkflowRunTool } from './src/tools/workflow-run.js';

function createTempProject() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vlcode-workflow-status-'));
  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 = () => {};

  const generateTool = createVLGenerateTool(server.config);
  const adjustTool = createVLAdjustTool(server.config);
  const workflowTool = createWorkflowRunTool(server.config);

  let status = JSON.parse(await generateTool.execute({ action: 'status' }));
  assert.equal(status.active, false);
  assert.equal(status.workflowName, null);
  assert.equal(status.projectName, path.basename(workDir));

  server.config._onWorkflowStart('3-file');
  server.config._onWorkflowNodeStatus('LLM_100_PRD', 'running');
  server.config._recordWorkflowEvent({
    type: 'wf_node_start',
    nodeId: 'LLM_100_PRD',
    title: 'PRD Analysis',
    nodeType: 'LLM',
    input: { docs: ['31'] },
  });

  status = JSON.parse(await generateTool.execute({ action: 'status' }));
  assert.equal(status.active, true);
  assert.equal(status.workflowName, '3-file');
  assert.equal(status.nodeStatuses.LLM_100_PRD, 'running');
  assert.equal(status.nodeDetails.LLM_100_PRD.title, 'PRD Analysis');
  assert.equal(status.timeline[0].type, 'wf_node_start');

  let adjustStatus = JSON.parse(await adjustTool.execute({ action: 'status' }));
  assert.equal(adjustStatus.active, true);
  assert.equal(adjustStatus.workflowName, '3-file');
  assert.equal(adjustStatus.nodeDetails.LLM_100_PRD.type, 'LLM');

  let workflowStatus = JSON.parse(await workflowTool.execute({ mode: 'status' }));
  assert.equal(workflowStatus.active, true);
  assert.equal(workflowStatus.workflowName, '3-file');
  assert.equal(workflowStatus.nodeDetails.LLM_100_PRD.status, 'running');

  server.config._onWorkflowDone();
  await new Promise((resolve) => setTimeout(resolve, 0));

  adjustStatus = JSON.parse(await adjustTool.execute({ action: 'status' }));
  assert.equal(adjustStatus.active, false);
  assert.equal(adjustStatus.workflowName, null);

  workflowStatus = JSON.parse(await workflowTool.execute({ mode: 'status' }));
  assert.equal(workflowStatus.active, false);
  assert.equal(workflowStatus.workflowName, null);

  fs.rmSync(workDir, { recursive: true, force: true });
  console.log('\n── Workflow Status Tools ──');
  console.log('PASS test-workflow-status-tools.js');
}

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