/**
 * Generate Test Cases Node - Generate human-readable test case specifications
 * Used by: analysisGraph, implementationGraph
 * 
 * Output: Plain-text test specifications for AI interpretation
 * - High-level test steps in natural language
 * - Includes credentials, prerequisites, and expected results
 * - Can be executed by AI agents (like MCP) and converted to Playwright
 */

import { invokeAgent } from '@zibby/core';
import { z } from 'zod';
import { randomBytes } from 'crypto';
import { adfToText } from '../../../dist/utils/adf-converter.js';

// Generate a simple unique ID
const generateId = () => randomBytes(8).toString('hex');

// Schema for plain-text test specification
const TestSpecificationSchema = z.object({
  id: z.string().optional(),
  title: z.string().describe('Test name (e.g., "Login Functionality", "Create New User")'),
  application: z.string().describe('Application name being tested'),
  url: z.string().describe('Base URL of the application'),
  testerRole: z.string().describe('Role performing the test (e.g., "Admin user", "End user")'),
  feature: z.string().describe('Feature being tested (e.g., "Authentication - Login")'),
  ticketId: z.string().describe('Associated ticket ID'),
  testCredentials: z.array(z.object({
    field: z.string().describe('Credential field name (e.g., "Email", "Password", "API Key")'),
    value: z.string().describe('Credential value')
  })).optional().describe('Test credentials needed (if any)'),
  testObjective: z.string().describe('One clear sentence: what this test verifies'),
  testSteps: z.array(z.string()).describe('Plain English steps - natural language instructions (e.g., "Navigate to /login", "Enter email: test@example.com", "Click the submit button")'),
  expectedResults: z.array(z.string()).describe('What should happen - bullet points of expected outcomes'),
  status: z.string().default('Ready for automation').describe('Test status'),
  priority: z.enum(['Critical', 'High', 'Medium', 'Low']).describe('Test priority'),
  category: z.string().describe('Test category (e.g., "Smoke Test", "Regression", "Integration")')
});

const CategoryCountSchema = z.object({
  category: z.string().describe('Category name'),
  count: z.number().describe('Number of tests in this category')
});

// Schema for AI agent output (what invokeAgent validates)
const TestSuiteSchema = z.object({
  testCases: z.array(TestSpecificationSchema).describe('Array of test specifications'),
  summary: z.object({
    totalTests: z.number(),
    byCategory: z.array(CategoryCountSchema).optional(),
    coverageNotes: z.string().optional()
  }).optional()
});

// Node output schema (what this node returns to state)
const GenerateTestCasesOutputSchema = z.object({
  success: z.boolean(),
  tests: z.object({
    structured: z.object({
      testCases: z.array(z.any()),
      summary: z.object({
        totalTests: z.number(),
        byCategory: z.array(CategoryCountSchema).optional()
      }).optional()
    }),
    timestamp: z.string()
  }).nullable()
});

export const generateTestCasesNode = {
  name: 'generate_test_cases',
  
  // Output schema defines what this node returns to state
  outputSchema: GenerateTestCasesOutputSchema,
  
  execute: async (state) => {
    console.log('\n🧪 Generating test cases...');
    
    const { ticketContext, workspace, model, nodeConfigs = {} } = state;
    const aiModel = model || ticketContext.model || 'auto';
    const codeImpl = state.generate_code?.codeImplementation ||
                     state.implement_code?.codeImplementation;
    
    if (!codeImpl || !codeImpl.diff) {
      console.log('⚠️  No code changes detected, skipping test generation');
      return {
        success: true,
        tests: null
      };
    }
    
    // Get node config for this node (if user configured it)
    const nodeConfig = nodeConfigs.generate_test_cases || {};
    console.log('📋 Node config:', JSON.stringify(nodeConfig, null, 2));
    
    // Build test generation prompt with workspace path for codebase exploration
    const testPrompt = buildTestGenerationPrompt(ticketContext, codeImpl, workspace, nodeConfig);
    
    console.log(`🚀 Running AI Agent to generate tests with model: ${aiModel}...`);
    
    const agentResult = await invokeAgent(testPrompt, { 
      state, 
      model: aiModel,
      schema: TestSuiteSchema
    });
    
    const validatedOutput = agentResult?.structured || agentResult;
    
    // Convert structured AI output → simple { id, title, priority, content } format
    const testCases = (validatedOutput?.testCases || []).map(test => ({
      id: generateId(),
      title: test.title,
      priority: test.priority || 'Medium',
      content: renderTestCaseToText(test),
      status: 'pending'
    }));
    
    console.log(`✅ Generated ${testCases.length} test cases`);
    
    return {
      success: true,
      tests: {
        structured: {
          testCases,
          summary: validatedOutput.summary || {
            totalTests: testCases.length,
            byCategory: Object.entries(
              testCases.reduce((acc, tc) => {
                acc[tc.category] = (acc[tc.category] || 0) + 1;
                return acc;
              }, {})
            ).map(([category, count]) => ({ category, count }))
          }
        },
        timestamp: new Date().toISOString()
      }
    };
  }
};

function renderTestCaseToText(test) {
  const lines = [];
  
  if (test.testObjective) {
    lines.push('WHAT THIS TESTS');
    lines.push(test.testObjective);
    lines.push('');
  }
  
  if (test.url) {
    lines.push('START URL');
    lines.push(test.url);
    lines.push('');
  }
  
  if (test.testCredentials && test.testCredentials.length > 0) {
    lines.push('TEST CREDENTIALS');
    test.testCredentials.forEach(cred => {
      lines.push(`• ${cred.field}: ${cred.value}`);
    });
    lines.push('');
  }
  
  if (test.testSteps && test.testSteps.length > 0) {
    lines.push('TEST STEPS');
    test.testSteps.forEach((step, i) => {
      lines.push(`${i + 1}. ${step}`);
    });
    lines.push('');
  }
  
  if (test.expectedResults && test.expectedResults.length > 0) {
    lines.push('EXPECTED RESULTS');
    test.expectedResults.forEach(result => {
      lines.push(`• ${result}`);
    });
  }
  
  return lines.join('\n').trim();
}

function buildTestGenerationPrompt(ticketContext, codeImpl, workspace, nodeConfig = {}) {
  // Extract user-provided context (test URL, admin credentials, etc.)
  const extractContext = nodeConfig.extractContext || {};
  let contextSection = '';
  if (extractContext.testBaseUrl || extractContext.adminUsername || extractContext.testAccountUsername) {
    contextSection = `
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PROVIDED TEST CONTEXT (USE THESE IN TEST CASES)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

${extractContext.testBaseUrl ? `Test Base URL: ${extractContext.testBaseUrl}` : ''}
${extractContext.adminUsername ? `Admin Username: ${extractContext.adminUsername}` : ''}
${extractContext.adminPassword ? `Admin Password: ${extractContext.adminPassword}` : ''}
${extractContext.testAccountUsername ? `Test Account Username: ${extractContext.testAccountUsername}` : ''}
${extractContext.testAccountPassword ? `Test Account Password: ${extractContext.testAccountPassword}` : ''}

**IMPORTANT**: Use these exact values in your test cases. Do NOT make up URLs or credentials.

`;
  }
  
  return `You are an AI test automation engineer creating human-readable test specifications.

WORKSPACE: ${workspace}

TICKET: ${ticketContext.ticketKey} - ${ticketContext.summary}
${ticketContext.description ? `Description: ${typeof ticketContext.description === 'object' ? adfToText(ticketContext.description) : ticketContext.description}` : ''}

MODIFIED FILES:
${codeImpl.changedFiles.map(f => `  - ${f}`).join('\n')}

FULL CODE DIFF:
\`\`\`diff
${codeImpl.diff}
\`\`\`

${contextSection}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

YOUR JOB: Generate 4-8 test specifications in plain-text format that AI agents can interpret.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
STEP 1: EXPLORE THE CODEBASE (MANDATORY - DO NOT SKIP)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

YOU MUST explore the codebase to understand the application structure BEFORE writing tests.

REQUIRED EXPLORATION:

1. **Find and Read Routing Files**
   - Search the workspace for routing files: look for common names like App, routes, router, main, index files in .js/.jsx/.ts/.tsx format
   - Check common locations: src/, app/, client/, web/, components/, pages/ directories
   - Identify ALL routes and their URL patterns
   - Pay special attention to routes with parameters (e.g., /stores/:storeId/products, /users/:userId/orders, /items/:itemId)
   
2. **Understand Route Parameters**
   - Dynamic segments in routes (marked with :paramName or {paramName}) are PLACEHOLDERS
   - You MUST include navigation steps to select/create that resource first
   - Example: To reach /stores/:storeId/products, you must first navigate to /stores list and select a specific store
   - Example: To reach /orders/:orderId/details, you must first navigate to /orders list and click on a specific order

3. **Map Navigation Flow**
   - Understand the hierarchy: authentication → landing/home → resource lists → individual resources → sub-features
   - Find what links, buttons, tabs exist on each page to navigate to the next level
   - Read page components to understand the UI structure and navigation elements

4. **Find Authentication**
   - Check for login/signin routes, auth components, protected routes, authentication guards
   - Look for HOCs, route wrappers, or middleware that handle authentication
   - Understand if authentication is required and what the login flow looks like

5. **Identify Page Components**
   - Find the actual page/view components referenced in routes
   - Read their code to understand imports, props, state management, and structure
   - Understand what data they load, what APIs they call, and what user actions they support

CRITICAL RULES:
- Routes with dynamic parameters (like :id, :userId, :orderId) REQUIRE parent resource selection
- You CANNOT jump directly to a URL with an ID - you must navigate through the parent list and SELECT that item
- Base your test steps on ACTUAL navigation paths you discover in the codebase
- If you don't explore properly, your tests will have WRONG navigation and be unusable by AI agents

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
STEP 2: GENERATE TEST SPECIFICATIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

For each test, provide:
- **title**: Test name (e.g., "Filter Orders by Status")
- **application**: Application name (infer from package.json or codebase)
- **url**: Base application URL (usually http://localhost:3000 or staging URL if found)
- **testerRole**: Who performs this test (e.g., "Admin user", "End user", "Guest")
- **feature**: Feature being tested (match the modified files)
- **ticketId**: Use the ticket key provided above
- **testCredentials**: Array of credentials needed (if authentication required):
  - field: "Email" / "Password" / "Username" / "API Key", etc.
  - value: Use realistic test data (e.g., "admin@example.com", "TestPass123")
- **testObjective**: One clear sentence describing what this test verifies
- **testSteps**: Plain English steps - MUST match actual navigation flow you discovered. Example:
  * "Navigate to login page http://localhost:3000/login"
  * "Enter email: admin@example.com"
  * "Enter password: TestPass123"
  * "Click the Sign In button"
  * "Navigate to Projects page http://localhost:3000/projects"
  * "Click on project 'Test Project 1'"
  * "Navigate to Orders tab"
  * "Click the status filter dropdown"
  * "Select 'Completed' from the filter"
  * "Verify only completed orders are displayed"
  DON'T use technical terms like "action", "target", "selector" - just natural language
- **expectedResults**: Bullet points of what should happen
- **priority**: Critical, High, Medium, or Low
- **category**: Test category (e.g., "Smoke Test", "Regression", "Integration")

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EXAMPLE: Multi-Level Navigation (Generic Restaurant Ordering App)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Assume this routing structure (discovered from App.jsx):
  /login
  /restaurants
  /restaurants/:restaurantId/menu
  /restaurants/:restaurantId/menu/:itemId/details

CORRECT Test Steps (follows nested structure):
{
  "title": "Add Menu Item to Cart with Size Selection",
  "application": "Restaurant Ordering System",
  "url": "http://localhost:3000",
  "testerRole": "Customer",
  "feature": "Menu - Item Size Selection",
  "ticketId": "REST-456",
  "testCredentials": [
    { "field": "Email", "value": "customer@email.com" },
    { "field": "Password", "value": "Order123" }
  ],
  "testObjective": "Verify customers can select different sizes when adding menu items to cart",
  "testSteps": [
    "Navigate to login page http://localhost:3000/login",
    "Enter email: customer@email.com",
    "Enter password: Order123",
    "Click the Sign In button",
    "Navigate to Restaurants page http://localhost:3000/restaurants",
    "Click on restaurant 'Downtown Pizza'",
    "Wait for menu to load",
    "Scroll to 'Beverages' section",
    "Click on menu item 'Lemonade'",
    "Wait for item details to display",
    "Click the size dropdown",
    "Select 'Large' size option",
    "Verify price updates to large size price",
    "Click Add to Cart button",
    "Verify item added to cart with Large size"
  ],
  "expectedResults": [
    "Size dropdown displays all available sizes (Small, Medium, Large)",
    "Price updates when different size is selected",
    "Item is added to cart with correct size",
    "Cart icon shows updated item count",
    "No errors displayed during the process"
  ],
  "priority": "High",
  "category": "Smoke Test"
}

WRONG Test Steps (skips required navigation):
  ❌ "Navigate to Menu page"  (Too vague - which restaurant?)
  ❌ "Go to /restaurants/123/menu"  (Can't directly use IDs without selection)
  ❌ "Select item from menu"  (Need to navigate to restaurant first)
  
CORRECT Test Steps (shows proper navigation):
  ✅ "Navigate to Restaurants page http://localhost:3000/restaurants"
  ✅ "Click on restaurant 'Downtown Pizza'"
  ✅ "Wait for menu to load"
  ✅ "Click on menu item 'Lemonade'"

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FINAL REMINDERS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. ALWAYS explore routing files FIRST
2. NEVER skip navigation steps - include full path from login to feature
3. If routes have :parameters, include parent resource selection
4. Use ACTUAL URLs and paths from the codebase
5. Write plain English steps - no technical jargon
6. Base tests on REAL navigation flow, not assumptions

Now generate test specifications for the ticket above.`;
}
/**
 * Agent Strategy Handling:
 * - Claude: Uses tool calling with schema → guaranteed structured output
 * - Cursor: Post-processes raw output with LangChain withStructuredOutput
 * 
 * Node receives validated structured data regardless of agent type.
 */

