import path from 'path';
import * as ts from 'typescript';

/**
 * Extracts React type definitions from node_modules for type checking
 * @returns {string[]} Array of React type names
 */
export default function extractReactTypes() {
  const reactTypesFile = path.resolve('node_modules/@types/react/index.d.ts');
  const program = ts.createProgram([reactTypesFile], { noEmit: true });
  const sourceFile = program.getSourceFile(reactTypesFile);

  if (!sourceFile) {
    console.error('Could not load React type definitions at:', reactTypesFile);
    return [];
  }

  const types = [];

  function extractTypeNames(node, prefix = '', insideReactNamespace = false) {
    if (ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)) {
      if (insideReactNamespace && node.name) {
        types.push(`${prefix}${node.name.text}`);
      } else {
        const isExported = node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword);
        if (isExported && node.name) {
          types.push(`${prefix}${node.name.text}`);
        }
      }
    } else if (ts.isModuleDeclaration(node) && node.name.text === 'React') {
      if (node.body && ts.isModuleBlock(node.body)) {
        node.body.statements.forEach(child => {
          extractTypeNames(child, 'React.', true);
        });
      }
    }

    node.forEachChild(child => extractTypeNames(child, prefix, insideReactNamespace));
  }

  sourceFile.forEachChild(node => extractTypeNames(node));
  return types.filter(type => !['React.Element', 'React.Key', 'React.MouseEvent'].includes(type));
}
