import { readFileSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { setupNode } from './nodes/setup-node.js';
import { analyzeTicketNode } from './nodes/analyze-ticket-node.js';
import { generateCodeNode } from './nodes/generate-code-node.js';
import { generateTestCasesNode } from './nodes/generate-test-cases-node.js';
import { finalizeNode } from './nodes/finalize-node.js';
import { analysisStateSchema } from './state.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const promptsDir = join(__dirname, 'prompts');

// Helper to load prompt if file exists
function loadPrompt(filename) {
  const path = join(promptsDir, filename);
  if (existsSync(path)) {
    return readFileSync(path, 'utf-8');
  }
  return null;
}

// Load prompt templates at graph definition time
const analyzeTicketPrompt = loadPrompt('analyze-ticket.md');
const generateCodePrompt = loadPrompt('generate-code.md');
const generateTestCasesPrompt = loadPrompt('generate-test-cases.md');

export function buildAnalysisGraph(graph) {
  graph.setStateSchema(analysisStateSchema);
  
  graph
    .addNode('setup', setupNode)
    .addNode('analyze_ticket', analyzeTicketNode, { 
      prompt: analyzeTicketPrompt 
    })
    .addConditionalNode('validation_check', {
      condition: (state) => {
        const validation = state.analyze_ticket?.validation;
        if (!validation?.canProceed) {
          return 'finalize';
        }
        return 'generate_code';
      }
    })
    .addNode('generate_code', generateCodeNode, { 
      prompt: generateCodePrompt 
    })
    .addNode('generate_test_cases', generateTestCasesNode, {
      prompt: generateTestCasesPrompt
    })
    .addNode('finalize', finalizeNode)
    .setNodeType('validation_check', 'decision')
    .setEntryPoint('setup')
    .addEdge('setup', 'analyze_ticket')
    .addEdge('analyze_ticket', 'validation_check')
    .addConditionalEdges('validation_check', (state) => {
      const validation = state.analyze_ticket?.validation || state.analyze_ticket_output?.validation;
      if (validation?.canProceed) {
        return 'generate_code';
      }
      return 'finalize';
    }, {
      labels: {
        generate_code: 'if valid',
        finalize: 'if invalid'
      }
    })
    .addEdge('generate_code', 'generate_test_cases')
    .addEdge('generate_test_cases', 'finalize');
  
  return graph;
}
