#!/usr/bin/env node

/**
 * View Schema Cache
 * Display the contents of the schema cache
 */

const { getCache } = require('./schema-cache');
const path = require('path');

async function viewCache(options = {}) {
  const { collection, field, stats, export: exportCache } = options;
  
  try {
    const cache = getCache();
    await cache.init();
    
    // Show stats
    if (stats) {
      const cacheStats = cache.getStats();
      console.log('📊 Cache Statistics:');
      console.log('='.repeat(40));
      console.log(`Initialized: ${cacheStats.initialized}`);
      console.log(`Last Sync: ${cacheStats.lastSync || 'Never'}`);
      console.log(`Last Modified: ${cacheStats.lastModified || 'Never'}`);
      console.log(`Total Collections: ${cacheStats.totalCollections}`);
      console.log(`  - System: ${cacheStats.systemCollections}`);
      console.log(`  - Custom: ${cacheStats.customCollections}`);
      console.log(`Total Fields: ${cacheStats.totalFields}`);
      console.log(`Total Relations: ${cacheStats.totalRelations}`);
      console.log(`Cache File: ${cacheStats.cacheFile}`);
      return;
    }
    
    // Export cache
    if (exportCache) {
      const exportFile = await cache.export();
      console.log(`✅ Cache exported to: ${exportFile}`);
      return;
    }
    
    // Show specific collection
    if (collection) {
      const collectionData = cache.getCollection(collection);
      
      if (!collectionData) {
        console.log(`❌ Collection '${collection}' not found in cache`);
        return;
      }
      
      console.log(`\n📦 Collection: ${collection}`);
      console.log('='.repeat(50));
      
      // Show specific field
      if (field) {
        const fieldData = cache.getField(collection, field);
        if (!fieldData) {
          console.log(`❌ Field '${field}' not found in collection '${collection}'`);
          return;
        }
        
        console.log(`\n📄 Field: ${field}`);
        console.log(JSON.stringify(fieldData, null, 2));
      } else {
        // Show all fields
        const fields = Object.keys(collectionData.fields || {});
        console.log(`Fields (${fields.length}):`);
        
        fields.forEach(fieldName => {
          const fieldData = collectionData.fields[fieldName];
          console.log(`  • ${fieldName} (${fieldData.type})`);
        });
      }
      return;
    }
    
    // Show all collections
    const cacheData = await cache.load();
    const collections = Object.keys(cacheData.collections);
    
    console.log('\n📚 Cached Collections:');
    console.log('='.repeat(50));
    
    // Separate system and custom collections
    const systemCollections = collections.filter(c => c.startsWith('directus_'));
    const customCollections = collections.filter(c => !c.startsWith('directus_'));
    
    if (customCollections.length > 0) {
      console.log('\n📦 Custom Collections:');
      customCollections.forEach(collectionName => {
        const collectionData = cacheData.collections[collectionName];
        const fieldCount = Object.keys(collectionData.fields || {}).length;
        console.log(`  • ${collectionName} (${fieldCount} fields)`);
      });
    }
    
    if (systemCollections.length > 0) {
      console.log('\n🔧 System Collections:');
      systemCollections.forEach(collectionName => {
        const collectionData = cacheData.collections[collectionName];
        const fieldCount = Object.keys(collectionData.fields || {}).length;
        console.log(`  • ${collectionName} (${fieldCount} fields)`);
      });
    }
    
    // Show relations summary
    if (cacheData.relations && cacheData.relations.length > 0) {
      console.log(`\n🔗 Relations: ${cacheData.relations.length}`);
      cacheData.relations.slice(0, 5).forEach(relation => {
        console.log(`  • ${relation.collection}.${relation.field} -> ${relation.related_collection}`);
      });
      if (cacheData.relations.length > 5) {
        console.log(`  ... and ${cacheData.relations.length - 5} more`);
      }
    }
    
    console.log('\n💡 Tips:');
    console.log('  • Use --collection=<name> to view specific collection');
    console.log('  • Use --collection=<name> --field=<name> to view specific field');
    console.log('  • Use --stats to view cache statistics');
    console.log('  • Use --export to export cache to JSON file');
    
  } catch (error) {
    console.error('❌ Failed to view cache:', error.message);
    process.exit(1);
  }
}

// Parse command line arguments
if (require.main === module) {
  const args = process.argv.slice(2);
  const options = {};
  
  args.forEach(arg => {
    if (arg.startsWith('--')) {
      const [key, value] = arg.slice(2).split('=');
      options[key] = value || true;
    }
  });
  
  viewCache(options);
}

module.exports = { viewCache };