/**
 * Block Registry Generator
 *
 * Generates block-registry.ts
 *
 * @module core/scripts/build/registry/generators/block-registry
 */

import { join } from 'path'
import { convertCorePath } from '../config.mjs'

/**
 * Generate the block registry file
 * @param {Array} blocks - Discovered blocks
 * @param {object} config - Configuration object from getConfig()
 * @returns {string} Generated TypeScript content
 */
export function generateBlockRegistry(blocks, config) {
  const outputFilePath = join(config.outputDir, 'block-registry.ts')
  if (blocks.length === 0) {
    return `/**
 * Auto-generated Block Registry
 *
 * Generated at: ${new Date().toISOString()}
 * Blocks discovered: 0
 *
 * DO NOT EDIT - This file is auto-generated by scripts/build-registry.mjs
 */

import type { BlockConfig } from '${convertCorePath('@/core/types/blocks', outputFilePath, config)}'

export const BLOCK_REGISTRY: Record<string, BlockConfig> = {}

export const BLOCK_CATEGORIES: string[] = []

export const BLOCK_METADATA = {
  totalBlocks: 0,
  categories: [],
  blocksByCategory: {},
  generatedAt: '${new Date().toISOString()}',
  blocks: []
}
`
  }

  // Import field definitions and examples (if they exist)
  const imports = []

  blocks.forEach(block => {
    const slugVar = block.slug.replace(/-/g, '_')

    // Always import field definitions
    imports.push(`import { fieldDefinitions as ${slugVar}_fields } from '${block.paths.fields}'`)

    // Conditionally import examples if they exist
    if (block.hasExamples) {
      imports.push(`import { examples as ${slugVar}_examples } from '${block.paths.examples}'`)
    }
  })

  const fieldImports = imports.join('\n')

  const registryEntries = blocks.map(block => {
    const slugVar = block.slug.replace(/-/g, '_')
    const scopeValue = block.scope
      ? `[${block.scope.map(s => `'${s}'`).join(', ')}]`
      : 'undefined'
    const examplesValue = block.hasExamples ? `${slugVar}_examples` : '[]'

    return `  '${block.slug}': {
    slug: '${block.slug}',
    name: '${block.name}',
    description: '${block.description}',
    category: '${block.category}' as BlockCategory,
    icon: '${block.icon}',
    componentPath: '${block.paths.component}',
    schemaPath: '${block.paths.schema}',
    fieldsPath: '${block.paths.fields}',
    thumbnail: ${block.paths.thumbnail ? `'${block.paths.thumbnail}'` : 'undefined'},
    fieldDefinitions: ${slugVar}_fields,
    examples: ${examplesValue},
    scope: ${scopeValue},
    isCore: false,
    source: 'theme' as const,
    sourceId: '${block.themeName}'
  }`
  }).join(',\n')

  const categories = [...new Set(blocks.map(b => b.category))]

  return `/**
 * Auto-generated Block Registry
 *
 * Generated at: ${new Date().toISOString()}
 * Blocks discovered: ${blocks.length}
 * Categories: ${categories.join(', ')}
 *
 * This registry provides build-time access to all block definitions.
 * Use this for admin UI (block picker, form generation) and API endpoints.
 *
 * DO NOT EDIT - This file is auto-generated by scripts/build-registry.mjs
 */

import React from 'react'
import type { BlockConfig, BlockCategory } from '${convertCorePath('@/core/types/blocks', outputFilePath, config)}'

${fieldImports}

export const BLOCK_REGISTRY: Record<string, BlockConfig> = {
${registryEntries}
}

export const BLOCK_CATEGORIES: BlockCategory[] = [${categories.map(c => `'${c}'`).join(', ')}]

/**
 * Lazy-loaded block components for runtime rendering
 * Each component is wrapped with React.lazy for code-splitting
 * Uses Object.values to get the first exported component (handles varying naming conventions)
 */
export const BLOCK_COMPONENTS: Record<string, React.LazyExoticComponent<React.ComponentType<any>>> = {
${blocks.map(block => {
    return `  '${block.slug}': React.lazy(() => import('${block.paths.component}').then(mod => ({ default: Object.values(mod)[0] as React.ComponentType<any> })))`
  }).join(',\n')}
}

/**
 * Block registry metadata
 */
export const BLOCK_METADATA = {
  totalBlocks: ${blocks.length},
  categories: [${categories.map(c => `'${c}'`).join(', ')}],
  blocksByCategory: {
${categories.map(cat => {
    const count = blocks.filter(b => b.category === cat).length
    return `    '${cat}': ${count}`
  }).join(',\n')}
  },
  generatedAt: '${new Date().toISOString()}',
  blocks: [${blocks.map(b => `'${b.slug}'`).join(', ')}]
}
`
}
