/**
 * Test Automation Workflow Graph
 * 
 * buildGraph() - define nodes, edges, routing
 * onComplete(result) - post-processing after graph finishes (save artifacts, etc.)
 */

import { WorkflowAgent, WorkflowGraph } from '@zibby/core';
import { 
  preflightNode, 
  executeLiveNode, 
  generateScriptNode,
} from './nodes/index.mjs';
import { BrowserTestResultHandler } from './result-handler.mjs';

export class BrowserTestAutomationAgent extends WorkflowAgent {
  buildGraph() {
    const graph = new WorkflowGraph();

    graph.addNode('preflight', preflightNode);
    graph.addNode('execute_live', executeLiveNode);
    graph.addNode('generate_script', generateScriptNode);
            
    graph.setEntryPoint('preflight');
    graph.addEdge('preflight', 'execute_live');
    
    graph.addConditionalEdges('execute_live', (state) => {
      const result = state.execute_live;
      const hasExecution = (result?.steps?.length > 0) || (result?.actions?.length > 0);
      return hasExecution ? 'generate_script' : 'END';
    });
    
    graph.addEdge('generate_script', 'END');
    return graph;
  }

  async onComplete(result) {
    const cwd = result.state.cwd || process.cwd();
    BrowserTestResultHandler.saveTitle(result, cwd);
    await BrowserTestResultHandler.saveExecutionData(result);
    BrowserTestResultHandler.ensureStudioCodegenMirror(
      result.state?.sessionPath,
      result.state?.cwd || cwd,
    );

    // Memory end-run hook (if @zibby/memory is installed)
    try {
      const { memoryEndRun, memorySyncPush } = await import('@zibby/memory');
      const sessionId = result.state.sessionPath?.split('/').pop();
      memoryEndRun(cwd, { sessionId, passed: result.success !== false });
      memorySyncPush(cwd);
    } catch { /* @zibby/memory not available */ }
  }
}
