#!/usr/bin/env tsx
/**
 * Test script to verify that parentExecutionId options are now working
 */

import { model, prompts } from '../src/typescript/simplified';
import * as path from 'path';
import * as fs from 'fs/promises';

async function testParentExecutionFix() {
    console.log('Testing parentExecutionId fix...');
    
    try {
        // First execution (parent)
        console.log('Creating parent execution...');
        const parentResponse = await model.complete(
            'gpt-4o-mini',
            'Say "This is the parent"',
            'parent-agent'
        );
        
        console.log(`Parent execution ID: ${parentResponse.executionId}`);
        
        // Second execution (child with explicit parentExecutionId)
        console.log('Creating child execution with explicit parentExecutionId...');
        const childResponse = await model.complete(
            'gpt-4o-mini', 
            'Say "This is the child"',
            'child-agent',
            undefined,
            {
                parentExecutionId: parentResponse.executionId
            }
        );
        
        console.log(`Child execution ID: ${childResponse.executionId}`);
        console.log(`Child specified parent ID: ${parentResponse.executionId}`);
        
        // Check if the child execution was stored with the correct parent ID
        const executionsDir = path.join(process.cwd(), '.pit', 'executions');
        const childFile = path.join(executionsDir, `${childResponse.executionId}.json`);
        
        // Wait a moment for file to be written
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        try {
            const childData = await fs.readFile(childFile, 'utf-8');
            const childExecution = JSON.parse(childData);
            
            console.log('\n=== CHILD EXECUTION DATA ===');
            console.log(`Execution ID: ${childExecution.id}`);
            console.log(`Tag: ${childExecution.tag}`);
            console.log(`Parent Execution ID: ${childExecution.parent_execution_id}`);
            console.log(`Chain Group ID: ${childExecution.chain_group_id}`);
            
            if (childExecution.parent_execution_id === parentResponse.executionId) {
                console.log('\n✅ SUCCESS! Parent execution ID is correctly stored.');
            } else {
                console.log('\n❌ FAILED! Parent execution ID is not correctly stored.');
                console.log(`Expected: ${parentResponse.executionId}`);
                console.log(`Actual: ${childExecution.parent_execution_id}`);
            }
            
        } catch (error) {
            console.error('Error reading child execution file:', error);
        }
        
    } catch (error) {
        console.error('Error in test:', error);
    }
}

testParentExecutionFix().catch(console.error);