#!/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: [],
  si: [],
  gi: [],
  tb: [],
  vsc: [],
  wi: [],
  aws: [],
  lucide: [],
};

for (const icon of iconNames) {
  if (icon.startsWith('Fa')) {
    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('Tb')) {
    iconsByLibrary.tb.push(icon);
  } else if (icon.startsWith('Vsc')) {
    iconsByLibrary.vsc.push(icon);
  } else if (icon.startsWith('Wi')) {
    iconsByLibrary.wi.push(icon);
  } else if (icon.startsWith('Aws')) {
    iconsByLibrary.aws.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";
`;

function iconImport(library, icons) {
  if (icons.length === 1) {
    return `import { ${icons[0]} } from "${library}";\n`;
  }

  return `import {\n  ${icons.join(",\n  ")},\n} from "${library}";\n`;
}

// Add react-icons imports
if (iconsByLibrary.fa.length > 0) {
  imports += iconImport("react-icons/fa", iconsByLibrary.fa);
}
if (iconsByLibrary.si.length > 0) {
  imports += iconImport("react-icons/si", iconsByLibrary.si);
}
if (iconsByLibrary.gi.length > 0) {
  imports += iconImport("react-icons/gi", iconsByLibrary.gi);
}
if (iconsByLibrary.tb.length > 0) {
  imports += iconImport("react-icons/tb", iconsByLibrary.tb);
}
if (iconsByLibrary.vsc.length > 0) {
  imports += iconImport("react-icons/vsc", iconsByLibrary.vsc);
}
if (iconsByLibrary.wi.length > 0) {
  imports += iconImport("react-icons/wi", iconsByLibrary.wi);
}
if (iconsByLibrary.aws.length > 0) {
  imports += iconImport("./awsIcons", iconsByLibrary.aws);
}

// 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.si) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.gi) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.tb) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.vsc) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.wi) {
  imports += `  ${icon},\n`;
}
for (const icon of iconsByLibrary.aws) {
  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.si.length} from react-icons/si`);
console.log(`   - ${iconsByLibrary.gi.length} from react-icons/gi`);
console.log(`   - ${iconsByLibrary.tb.length} from react-icons/tb`);
console.log(`   - ${iconsByLibrary.vsc.length} from react-icons/vsc`);
console.log(`   - ${iconsByLibrary.wi.length} from react-icons/wi`);
console.log(`   - ${iconsByLibrary.aws.length} from local AWS icons`);
console.log(`   - ${iconsByLibrary.lucide.length} from lucide-react`);
console.log(`📁 Output: ${outputPath}`);
