#!/usr/bin/env tsx
/**
 * Query parent-child relationships from the executions table
 */

import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
import * as path from 'path';
import crypto from 'crypto';

// Load environment variables
dotenv.config({ path: path.resolve(process.cwd(), '.env') });

async function queryParentChildRelationships() {
    const url = process.env.PIT_SUPABASE_URL;
    const serviceKey = process.env.PIT_SUPABASE_SERVICE_ROLE_KEY;
    const repoKey = process.env.PIT_REPO_KEY;

    if (!url || !serviceKey || !repoKey) {
        throw new Error('Missing required environment variables');
    }

    const supabaseClient = createClient(url, serviceKey);
    
    // Get repo_id
    const keyHash = crypto.createHash('sha256').update(repoKey).digest('hex');
    const { data: keyData } = await supabaseClient
        .from('repo_keys')
        .select('repo_id')
        .eq('key_hash', keyHash)
        .single();

    if (!keyData) throw new Error('Invalid repository key');
    
    console.log('Repository ID:', keyData.repo_id);

    // Get all chain execution groups for session-analysis-pipeline
    const { data: chainGroups } = await supabaseClient
        .from('chain_execution_groups')
        .select('id, group_id, status')
        .eq('repo_id', keyData.repo_id)
        .eq('chain_id', 'session-analysis-pipeline');

    console.log(`\nFound ${chainGroups?.length || 0} chain execution groups`);

    if (!chainGroups || chainGroups.length === 0) return;

    for (const group of chainGroups) {
        console.log(`\n=== Chain Group ${group.group_id} (${group.status}) ===`);
        
        // Get all executions for this chain group
        const { data: executions } = await supabaseClient
            .from('executions')
            .select('id, tag, parent_execution_id, created_at')
            .eq('chain_group_id', group.id)
            .order('created_at', { ascending: true });

        if (!executions || executions.length === 0) {
            console.log('No executions found');
            continue;
        }

        console.log(`Found ${executions.length} executions:`);
        
        // Build parent-child map
        const executionMap = new Map();
        const childrenMap = new Map();
        
        executions.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.created_at).toLocaleTimeString();
            console.log(`${indent}├── ${exec.tag} [${exec.id.slice(0, 8)}...] (${timeStr})`);
            
            const children = childrenMap.get(exec.id) || [];
            children.forEach((child: any, index: number) => {
                const isLast = index === children.length - 1;
                const newIndent = indent + (isLast ? '    ' : '│   ');
                printTree(child, newIndent);
            });
        };

        // Find root executions (no parent)
        const rootExecutions = executions.filter(e => !e.parent_execution_id);
        rootExecutions.forEach(root => {
            printTree(root);
        });

        // Print raw relationships for verification
        console.log('\nRaw parent-child relationships:');
        executions.forEach(exec => {
            const parent = exec.parent_execution_id 
                ? executionMap.get(exec.parent_execution_id)?.tag 
                : 'ROOT';
            console.log(`  ${exec.tag} → parent: ${parent}`);
        });
    }
}

queryParentChildRelationships().catch(console.error);