#!/usr/bin/env tsx
/**
 * Check executions with token data
 */

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

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

async function main() {
  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, error: keyError } = await supabaseClient
    .from('repo_keys')
    .select('repo_id')
    .eq('key_hash', keyHash)
    .single();

  if (keyError || !keyData) {
    throw new Error('Invalid repository key');
  }

  const repoId = keyData.repo_id;
  console.log('Repository ID:', repoId);

  // Get all executions from the recent chain groups
  const { data: executions, error } = await supabaseClient
    .from('executions')
    .select('*')
    .eq('repo_id', repoId)
    .order('created_at', { ascending: false })
    .limit(20);

  if (error) {
    console.error('Error fetching executions:', error);
    return;
  }

  console.log(`\nFound ${executions?.length || 0} recent executions:\n`);
  
  for (const exec of executions || []) {
    console.log(`Execution: ${exec.id.substring(0, 12)}...`);
    console.log(`  Tag: ${exec.tag}`);
    console.log(`  Chain Group ID: ${exec.chain_group_id ? exec.chain_group_id.substring(0, 12) + '...' : 'None'}`);
    console.log(`  Tokens: ${JSON.stringify(exec.tokens)}`);
    console.log(`  Created: ${exec.created_at}`);
    console.log();
  }
}

main().catch(console.error);