#!/bin/bash

# Verify Collector Handoff Data
# This script checks if the collector handoff contract is properly persisted

set -e

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

PROJECT_ID="lyOZxelSkjAB6XisIzup"
TOKEN="Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjM4MDI5MzRmZTBlZWM0NmE1ZWQwMDA2ZDE0YTFiYWIwMWUzNDUwODMiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiTWFyayBIZW5kZXJzb24iLCJwaWN0dXJlIjoiaHR0cHM6Ly9hdmF0YXJzLmdpdGh1YnVzZXJjb250ZW50LmNvbS91LzUzOTU0MjEzP3Y9NCIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9nZW4tbGFuZy1jbGllbnQtMDk4MDA3OTQxMCIsImF1ZCI6Imdlbi1sYW5nLWNsaWVudC0wOTgwMDc5NDEwIiwiYXV0aF90aW1lIjoxNzYzMzI1MDEyLCJ1c2VyX2lkIjoiMmhDdmdXQzJaV2RJMGVlTm5SQVM3SWVKcmg1MiIsInN1YiI6IjJoQ3ZnV0MyWldkSTBlZU5uUkFTN0llSnJoNTIiLCJpYXQiOjE3NjM0MjI1NDUsImV4cCI6MTc2MzQyNjE0NSwiZW1haWwiOiJtYXJrQGdldGFjcXVpcmVkLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJnaXRodWIuY29tIjpbIjUzOTU0MjEzIl0sImVtYWlsIjpbIm1hcmtAZ2V0YWNxdWlyZWQuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoiZ2l0aHViLmNvbSJ9fQ.TpMOORDnPUKkbLlg-KtYBmbarEjAijJ3W4vN8tWT6OslOfwaeDJAtPXIahyQk38UvKY4ZGognQG6t-laSATB8yIC8IdkYbD699axfPSGQqC8Lbux1P6YrFKOPLGDD2XemBtJ-Gb5Ql-nK_DbXKAmygLxIwz019XpLJEucGkBPAN_Rj2xC7125DVexkDSIb6ZnbLiDgCpR_IkImyQb08tqlOoBiHVUa-4VGDhraoBPACJfQXwPToJ1W3nhBiVtMvSq7s_Ekd8Otn8AB_1teu5lxC-rhLdgJuNrmlxO-H6xIMBFZ72bwq7wrvdWd_EijqFQCU99oEhphTNoISoJ3wK-g"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Verifying Collector Handoff Data${NC}"
echo -e "${BLUE}========================================${NC}\n"

# Create a temp Node.js script to check Firestore directly
cat > /tmp/check-handoff.js << 'EOFJS'
const admin = require('firebase-admin');

// Initialize Firebase Admin
const serviceAccount = require(process.env.HOME + '/ai-proxy/vibn-frontend/gen-lang-client-0980079410-firebase-adminsdk-fbsvc-c0e0cffc47.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  storageBucket: 'gen-lang-client-0980079410.firebasestorage.app'
});

const db = admin.firestore();

async function checkHandoff() {
  const projectId = process.argv[2];
  
  console.log(`\nChecking project: ${projectId}\n`);
  
  // 1. Check project document for phaseData
  const projectDoc = await db.collection('projects').doc(projectId).get();
  
  if (!projectDoc.exists) {
    console.log('❌ Project not found');
    process.exit(1);
  }
  
  const projectData = projectDoc.data();
  
  console.log('📋 Project Phase Info:');
  console.log(`  Current Phase: ${projectData.currentPhase || 'not set'}`);
  console.log(`  Phase Status: ${projectData.phaseStatus || 'not set'}`);
  
  // 2. Check for collector handoff data
  if (projectData.phaseData && projectData.phaseData.phaseHandoffs && projectData.phaseData.phaseHandoffs.collector) {
    const handoff = projectData.phaseData.phaseHandoffs.collector;
    console.log('\n✅ Collector Handoff Data Found:');
    console.log(JSON.stringify(handoff, null, 2));
    
    // Verify the handoff contract
    console.log('\n📊 Handoff Contract Status:');
    console.log(`  ✓ Has Documents: ${handoff.confirmed?.hasDocuments || false}`);
    console.log(`  ✓ Document Count: ${handoff.confirmed?.documentCount || 0}`);
    console.log(`  ✓ GitHub Connected: ${handoff.confirmed?.githubConnected || false}`);
    console.log(`  ✓ Extension Linked: ${handoff.confirmed?.extensionLinked || false}`);
    console.log(`  ✓ Ready for Extraction: ${handoff.readyForNextPhase || false}`);
    
    if (handoff.readyForNextPhase) {
      console.log('\n🎉 Collector phase is complete and ready for extraction!');
    } else {
      console.log('\n⏳ Collector phase is still in progress');
    }
  } else {
    console.log('\n⚠️  No collector handoff data found');
    console.log('   This might be normal if the AI hasn\'t returned structured handoff data yet');
  }
  
  // 3. Check knowledge items
  const knowledgeSnapshot = await db.collection('knowledge_items')
    .where('projectId', '==', projectId)
    .get();
  
  console.log(`\n📚 Knowledge Items: ${knowledgeSnapshot.size} found`);
  
  if (knowledgeSnapshot.size > 0) {
    knowledgeSnapshot.forEach(doc => {
      const data = doc.data();
      console.log(`  - ${data.title || 'Untitled'} (${data.sourceType})`);
    });
  }
  
  process.exit(0);
}

checkHandoff().catch(err => {
  console.error('Error:', err);
  process.exit(1);
});
EOFJS

echo -e "${YELLOW}Checking Firestore for handoff data...${NC}\n"

# Run the Node.js script
cd /Users/markhenderson/ai-proxy/vibn-frontend && node /tmp/check-handoff.js "$PROJECT_ID"

# Clean up
rm -f /tmp/check-handoff.js

echo -e "\n${BLUE}========================================${NC}"

