/**
 * Preflight Node
 * 
 * Pattern: Prompt-only node (no tools)
 * Purpose: Analyze test spec and extract title + structured assertion checklist
 * 
 * This runs before execution to define:
 * - A concise test title
 * - The complete list of assertions that must be verified
 * 
 * Downstream nodes receive this as their contract:
 * - execute_live: must report passed/failed for each assertion
 * - generate_script: must implement each assertion in the test
 */

import { z } from '@zibby/core';
import { writeFileSync } from 'fs';
import { join } from 'path';

const AssertionSchema = z.object({
  description: z.string().describe('What to verify (e.g., "User is redirected to dashboard")'),
  expected: z.string().describe('What the expected outcome looks like (e.g., "URL contains /dashboard")')
});

const PreflightOutputSchema = z.object({
  title: z.string().describe('Concise test title (5-10 words, action-oriented). Prefix with ticket ID if found.'),
  assertions: z.array(AssertionSchema).describe('Every expected result from the spec as a verifiable assertion')
});

export const preflightNode = {
  name: 'preflight',

  async onComplete(state, result) {
    const sessionPath = state.sessionPath || process.env.ZIBBY_SESSION_PATH;
    if (sessionPath && result.title) {
      try {
        writeFileSync(join(sessionPath, 'title.txt'), result.title, 'utf-8');
        console.log(`Saved title: "${result.title}"`);
      } catch (error) {
        console.warn(`⚠️  Could not save title.txt: ${error.message}`);
      }
    }
    return result;
  },

  prompt: (state) => `Analyze this test specification and extract:
1. A concise test title (5-10 words, action-oriented). If you find a ticket ID (e.g., PROJ-123, ACME-456), prefix the title with it.
2. Every expected result as a verifiable assertion. Each assertion must be something the browser can check after execution.

Test Spec:
${state.testSpec}

IMPORTANT: You MUST create ONE assertion for EACH expected result in the spec. Do NOT skip any.

Return ONLY this JSON:
{ "title": "TICKET-ID: Short action title", "assertions": [ { "description": "...", "expected": "..." }, ... ] }`,

  outputSchema: PreflightOutputSchema
};
