#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// Read tools metadata
const toolsMetadataPath = path.join(__dirname, '../../src/mindroom/tools_metadata.json');
const toolsMetadata = JSON.parse(fs.readFileSync(toolsMetadataPath, 'utf8'));

// Extract all unique icon names
const iconNames = new Set();
for (const tool of toolsMetadata.tools) {
  if (tool.icon) {
    iconNames.add(tool.icon);
  }
}

// Group icons by library
const iconsByLibrary = {
  fa: [],
  fa6: [],
  si: [],
  gi: [],
  vsc: [],
  lucide: []
};

// Icons we know exist in fa6 instead of fa
const fa6Icons = ['FaConfluence', 'FaLinear'];

for (const icon of iconNames) {
  if (icon.startsWith('Fa')) {
    if (fa6Icons.includes(icon)) {
      iconsByLibrary.fa6.push(icon);
    } else {
      iconsByLibrary.fa.push(icon);
    }
  } else if (icon.startsWith('Si')) {
    iconsByLibrary.si.push(icon);
  } else if (icon.startsWith('Gi')) {
    iconsByLibrary.gi.push(icon);
  } else if (icon.startsWith('Vsc')) {
    iconsByLibrary.vsc.push(icon);
  } else {
    // Assume it's a lucide icon
    iconsByLibrary.lucide.push(icon);
  }
}

// Generate the imports
let imports = `// THIS FILE IS AUTO-GENERATED - DO NOT EDIT MANUALLY
// Generated by scripts/generate-icon-imports.js from tools_metadata.json

import React, { createElement } from 'react';
import * as LucideIcons from 'lucide-react';
`;

// Add react-icons imports
if (iconsByLibrary.fa.length > 0) {
  imports += `import {\n  ${iconsByLibrary.fa.join(',\n  ')}\n} from 'react-icons/fa';\n`;
}
if (iconsByLibrary.fa6.length > 0) {
  // Note: FaLinear doesn't exist, we'll handle it in the mapping
  const existingFa6 = iconsByLibrary.fa6.filter(icon => icon !== 'FaLinear');
  if (existingFa6.length > 0) {
    imports += `import {\n  ${existingFa6.join(',\n  ')}\n} from 'react-icons/fa6';\n`;
  }
}
if (iconsByLibrary.si.length > 0) {
  imports += `import {\n  ${iconsByLibrary.si.join(',\n  ')}\n} from 'react-icons/si';\n`;
}
if (iconsByLibrary.gi.length > 0) {
  // GiGift doesn't exist in react-icons, skip it
  const existingGi = iconsByLibrary.gi.filter(icon => icon !== 'GiGift');
  if (existingGi.length > 0) {
    imports += `import {\n  ${existingGi.join(',\n  ')}\n} from 'react-icons/gi';\n`;
  }
}
if (iconsByLibrary.vsc.length > 0) {
  imports += `import {\n  ${iconsByLibrary.vsc.join(',\n  ')}\n} from 'react-icons/vsc';\n`;
}

// Create the icon mapping
imports += `
// Map of all icons we use
const iconMap: Record<string, any> = {
`;

// Add all the imported icons to the map
for (const icon of iconsByLibrary.fa) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.fa6) {
  if (icon === 'FaLinear') {
    // Use a fallback for FaLinear
    imports += `  FaLinear: LucideIcons.ListTodo, // Fallback icon\n`;
  } else {
    imports += `  ${icon},\n`;
  }
}
for (const icon of iconsByLibrary.si) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.gi) {
  if (icon === 'GiGift') {
    // Use a fallback for GiGift
    imports += `  GiGift: LucideIcons.Gift, // Fallback icon\n`;
  } else {
    imports += `  ${icon},\n`;
  }
}
for (const icon of iconsByLibrary.vsc) {
  imports += `  ${icon},\n`;
}

imports += `};

/**
 * Get the appropriate icon for a tool
 * @param iconName - The icon name from backend (e.g., "FaGithub", "Calculator", "Globe")
 * @param iconColor - The color class from backend (e.g., "text-blue-500")
 * @returns React element of the icon or default Globe icon
 */
export function getIconForTool(
  iconName: string | null,
  iconColor?: string | null
): React.ReactNode {
  const className = \`h-5 w-5 \${iconColor || ''}\`.trim();

  if (!iconName) {
    return createElement(LucideIcons.Globe, { className });
  }

  // Check react-icons map
  if (iconMap[iconName]) {
    return createElement(iconMap[iconName], { className });
  }

  // Check if it's a Lucide icon
  const lucideIcon = (LucideIcons as any)[iconName] || (LucideIcons as any)[iconName + 'Icon'];
  if (lucideIcon) {
    return createElement(lucideIcon, { className });
  }

  // Fallback to Globe icon
  console.warn(\`Icon "\${iconName}" not found, using default\`);
  return createElement(LucideIcons.Globe, { className });
}

// Export specific lucide icons that might be needed elsewhere
export const {
  Calculator,
  Folder,
  Terminal,
  Code,
  Book,
  Globe,
  Search,
  Newspaper,
  TrendingUp,
  FileText,
  Database,
  Mail,
  Film,
  VolumeX,
  Volume2,
} = LucideIcons;
`;

// Write the generated file
const outputPath = path.join(__dirname, '../src/components/Integrations/iconMapping.tsx');
fs.writeFileSync(outputPath, imports, 'utf8');

console.log(`✅ Generated icon imports for ${iconNames.size} unique icons`);
console.log(`   - ${iconsByLibrary.fa.length} from react-icons/fa`);
console.log(`   - ${iconsByLibrary.fa6.length} from react-icons/fa6`);
console.log(`   - ${iconsByLibrary.si.length} from react-icons/si`);
console.log(`   - ${iconsByLibrary.gi.length} from react-icons/gi`);
console.log(`   - ${iconsByLibrary.vsc.length} from react-icons/vsc`);
console.log(`   - ${iconsByLibrary.lucide.length} from lucide-react`);
console.log(`📁 Output: ${outputPath}`);
