/**
 * Script to update Storybook story categories according to the new hierarchical structure
 *
 * Usage:
 * 1. Run with Node.js: node update-story-categories.js
 * 2. The script will scan all .stories.ts files and suggest category updates
 * 3. You can review and apply the changes
 */

const fs = require('fs');
const path = require('path');
const {execSync} = require('child_process');

// Define the mapping from old categories to new categories
const categoryMapping = {
  // UI Components

  'Chatbot/ExportChatButton': 'UI/Buttons/ExportChatButton',
  'Components/MainButton': 'UI/Buttons/MainButton',
  'Components/AlertBox': 'UI/Feedback/AlertBox',
  'Components/Logo': 'Design/Brand/Logo',
  'Components/ColorDisplay': 'Design/Colors/ColorDisplay',
  'Components/FeedbackButton': 'UI/Feedback/FeedbackButton',
  'Components/ToggleButton': 'UI/Buttons/ToggleButton',

  // Chatbot Components
  'Chatbot/ConversationItem': 'Chatbot/Conversation/ConversationItem',
  'Chatbot/WarningBugs': 'Chatbot/Feedback/WarningBugs',
  'Components/MessageBox': 'Chatbot/Messages/MessageBox',
  'Components/PromptInput': 'Chatbot/Input/PromptInput',
  'Components/NewInput': 'Chatbot/Input/NewInput',
  'Components/SourceBlock': 'Chatbot/Sources/SourceBlock',

  // Navigation
  'Navigation/DsNavbar': 'UI/Navigation/Navbar',

  // App
  'App/Chatbot': 'App/Features/Chatbot',
};

// Find all story files
const findStoryFiles = () => {
  try {
    const result = execSync(
      'find /home/poule/encrypted/stockage-syncable/www/development/html/ng-implementation/old-sae-airwatch/src -name "*.stories.ts"'
    ).toString();
    return result.split('\n').filter(Boolean);
  } catch (error) {
    console.error('Error finding story files:', error);
    return [];
  }
};

// Extract current category from a story file
const extractCurrentCategory = (filePath) => {
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    const match = content.match(/title:\s*['"]([^'"]+)['"]/);
    return match ? match[1] : null;
  } catch (error) {
    console.error(`Error reading file ${filePath}:`, error);
    return null;
  }
};

// Update category in a story file
const updateCategory = (filePath, oldCategory, newCategory) => {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    content = content.replace(
      `title: '${oldCategory}'`,
      `title: '${newCategory}'`
    );
    fs.writeFileSync(filePath, content, 'utf8');
    console.log(`✅ Updated ${filePath}: ${oldCategory} -> ${newCategory}`);
    return true;
  } catch (error) {
    console.error(`Error updating file ${filePath}:`, error);
    return false;
  }
};

// Main function
const main = () => {
  console.log('🔍 Finding story files...');
  const storyFiles = findStoryFiles();
  console.log(`Found ${storyFiles.length} story files.`);

  let updated = 0;
  let skipped = 0;
  let notMapped = 0;

  storyFiles.forEach(filePath => {
    const currentCategory = extractCurrentCategory(filePath);
    if (!currentCategory) {
      console.log(`⚠️ Could not extract category from ${filePath}`);
      skipped++;
      return;
    }

    const newCategory = categoryMapping[currentCategory];
    if (!newCategory) {
      console.log(`ℹ️ No mapping defined for category: ${currentCategory} in ${filePath}`);
      notMapped++;
      return;
    }

    if (currentCategory === newCategory) {
      console.log(`ℹ️ Category already up to date: ${currentCategory} in ${filePath}`);
      skipped++;
      return;
    }

    const success = updateCategory(filePath, currentCategory, newCategory);
    if (success) {
      updated++;
    } else {
      skipped++;
    }
  });

  console.log('\n📊 Summary:');
  console.log(`Total files: ${storyFiles.length}`);
  console.log(`Updated: ${updated}`);
  console.log(`Skipped: ${skipped}`);
  console.log(`Not mapped: ${notMapped}`);

  if (notMapped > 0) {
    console.log('\n⚠️ Some categories were not mapped. Please update the categoryMapping object in the script.');
  }
};

// Run the script
main();
