const admin = require('firebase-admin');

// Initialize Firebase Admin
const serviceAccount = require('./vibn-firebase-admin-key.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

async function checkDocuments() {
  try {
    // Get the most recent project
    const projectsSnapshot = await db.collection('projects')
      .orderBy('createdAt', 'desc')
      .limit(1)
      .get();
    
    if (projectsSnapshot.empty) {
      console.log('No projects found');
      return;
    }
    
    const project = projectsSnapshot.docs[0];
    const projectId = project.id;
    const projectData = project.data();
    
    console.log('\n=== PROJECT INFO ===');
    console.log('Project ID:', projectId);
    console.log('Project Name:', projectData.name);
    console.log('Current Phase:', projectData.currentPhase);
    
    // Check knowledge_items
    console.log('\n=== KNOWLEDGE ITEMS ===');
    const knowledgeSnapshot = await db.collection('knowledge_items')
      .where('projectId', '==', projectId)
      .get();
    
    console.log('Total knowledge items:', knowledgeSnapshot.size);
    
    knowledgeSnapshot.docs.forEach((doc, idx) => {
      const data = doc.data();
      console.log(`\n[${idx + 1}] ${doc.id}`);
      console.log('  Title:', data.title);
      console.log('  Source Type:', data.sourceType);
      console.log('  Content Length:', data.content?.length || 0);
      console.log('  Created:', data.createdAt?.toDate?.() || 'unknown');
    });
    
    // Check extraction handoff
    console.log('\n=== EXTRACTION HANDOFF ===');
    const extractionHandoff = projectData.phaseData?.phaseHandoffs?.extraction;
    if (extractionHandoff) {
      console.log('Phase:', extractionHandoff.phase);
      console.log('Ready:', extractionHandoff.readyForNextPhase);
      console.log('Confidence:', extractionHandoff.confidence);
      console.log('Problems:', extractionHandoff.confirmed?.problems?.length || 0);
      console.log('Features:', extractionHandoff.confirmed?.features?.length || 0);
      console.log('Users:', extractionHandoff.confirmed?.targetUsers?.length || 0);
      console.log('Missing:', extractionHandoff.missing);
      console.log('Questions:', extractionHandoff.questionsForUser);
    } else {
      console.log('No extraction handoff found');
    }
    
  } catch (error) {
    console.error('Error:', error);
  } finally {
    process.exit(0);
  }
}

checkDocuments();
