#!/usr/bin/env node
import assert from 'assert';
import { WorkflowBuilder } from './src/tools/autotest/workflow-builder.js';

console.log('\n── AutoTest Parallel Workflow Builder ──');

const multiPagePlan = {
  appName: 'CampusTaskApp',
  appId: 'CampusTaskApp',
  homePage: '/TaskList',
  pages: [
    { path: '/TaskList', name: 'Task List', navPath: [] },
    { path: '/TaskPublish', name: 'Task Publish', navPath: ['vlid:publishTab'] },
    { path: '/TaskStats', name: 'Task Stats', navPath: ['vlid:statsTab'] },
  ],
  criticalPaths: [
    { name: 'Task filter flow', priority: 'P0' },
    { name: 'Task publish flow', priority: 'P0' },
  ],
};

const targets = WorkflowBuilder.planCaseGenerationTargets(multiPagePlan, 5);
assert.equal(targets.length, 3, 'multi-page plans should fan out to page targets');
assert.deepEqual(targets.map((target) => target.maxCases), [2, 2, 1], 'maxCases should be distributed across targets');
assert.equal(targets[0].kind, 'page');

const parallel = WorkflowBuilder.buildCaseGenerationWorkflow({
  testPlan: multiPagePlan,
  baseUrl: 'https://example.test/app',
  maxCases: 5,
  appId: 'CampusTaskApp',
  componentInfo: '- filterBtn (button) id="filterBtn" -> vlid:filterBtn',
});

const forkStep = parallel.wfJson.steps.find((step) => step.id === 'Fork_GenCaseTargets');
assert(forkStep, 'parallel workflow should create a Fork node');
assert.equal(forkStep.children.length, 3, 'fork should contain one branch per target');
assert.equal(parallel.outputVars.length, 3, 'parallel workflow should expose one output var per branch');
assert(parallel.wfJson.steps.some((step) => step.id === 'LLM_GenTestCases_001' && step.next === 'RETURN'), 'parallel child steps should return into the fork');

const singlePagePlan = {
  appName: 'SinglePageApp',
  appId: 'SinglePageApp',
  homePage: '/Home',
  pages: [
    { path: '/Home', name: 'Home', navPath: [] },
  ],
  criticalPaths: [
    { name: 'Search flow', priority: 'P0' },
  ],
};

const serial = WorkflowBuilder.buildCaseGenerationWorkflow({
  testPlan: singlePagePlan,
  baseUrl: 'https://example.test/app',
  maxCases: 4,
  appId: 'SinglePageApp',
  componentInfo: '',
});

assert.equal(serial.outputVars.length, 1, 'single-page plans should stay serial');
assert.equal(serial.wfJson.steps[0].id, 'LLM_GenTestCases', 'serial workflow should use a single LLM step');

console.log('PASS test-autotest-parallel-workflow-builder.js');
