#!/usr/bin/env tsx
/**
 * Debug parent-child relationships by examining local execution files
 */

import * as fs from 'fs/promises';
import * as path from 'path';

async function debugParentRelationships() {
    const executionsDir = path.join(process.cwd(), '.pit', 'executions');
    
    try {
        const files = await fs.readdir(executionsDir);
        const executionFiles = files.filter(f => f.endsWith('.json'));
        
        console.log(`Found ${executionFiles.length} execution files`);
        
        const executions = [];
        for (const file of executionFiles) {
            try {
                const data = await fs.readFile(path.join(executionsDir, file), 'utf-8');
                const execution = JSON.parse(data);
                executions.push(execution);
            } catch (error) {
                console.error(`Error reading ${file}:`, error);
            }
        }
        
        // Sort by timestamp
        executions.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
        
        // Filter for session-analysis-pipeline
        const sessionExecutions = executions.filter(e => 
            e.chain_id?.includes('session-analysis') || 
            e.tag?.includes('analysis') || 
            e.tag?.includes('agent')
        );
        
        console.log(`Found ${sessionExecutions.length} session analysis executions`);
        
        // Group by chain_group_id
        const groups = new Map();
        sessionExecutions.forEach(exec => {
            if (exec.chain_group_id) {
                if (!groups.has(exec.chain_group_id)) {
                    groups.set(exec.chain_group_id, []);
                }
                groups.get(exec.chain_group_id).push(exec);
            }
        });
        
        console.log(`Found ${groups.size} chain groups`);
        
        for (const [groupId, execs] of groups) {
            console.log(`\n=== Chain Group ${groupId.slice(0, 20)}... ===`);
            
            const executionMap = new Map();
            const childrenMap = new Map();
            
            execs.forEach(exec => {
                executionMap.set(exec.id, exec);
                if (exec.parent_execution_id) {
                    if (!childrenMap.has(exec.parent_execution_id)) {
                        childrenMap.set(exec.parent_execution_id, []);
                    }
                    childrenMap.get(exec.parent_execution_id).push(exec);
                }
            });
            
            // Print tree structure
            const printTree = (exec: any, indent = '') => {
                const timeStr = new Date(exec.timestamp).toLocaleTimeString();
                console.log(`${indent}├── ${exec.tag} [${exec.id.slice(0, 8)}...] (${timeStr})`);
                console.log(`${indent}    parent_id: ${exec.parent_execution_id ? exec.parent_execution_id.slice(0, 8) + '...' : 'NULL'}`);
                
                const children = childrenMap.get(exec.id) || [];
                children.forEach((child: any) => {
                    printTree(child, indent + '│   ');
                });
            };
            
            // Find root executions (no parent)
            const rootExecutions = execs.filter(e => !e.parent_execution_id);
            rootExecutions.forEach(root => {
                printTree(root);
            });
            
            // Check for orphaned executions
            const allParentIds = new Set(execs.map(e => e.parent_execution_id).filter(Boolean));
            const allIds = new Set(execs.map(e => e.id));
            const orphanedParentIds = Array.from(allParentIds).filter(pid => !allIds.has(pid));
            
            if (orphanedParentIds.length > 0) {
                console.log(`\nOrphaned parent IDs (parent not in this group): ${orphanedParentIds.length}`);
                orphanedParentIds.forEach(pid => console.log(`  - ${pid?.slice(0, 8)}...`));
            }
        }
        
    } catch (error) {
        console.error('Error reading executions:', error);
    }
}

debugParentRelationships().catch(console.error);