/**
 * rehype-fountain
 * 
 * A rehype plugin for processing Fountain screenplay notation code blocks.
 * This plugin finds code blocks with language "fountain", extracts their content,
 * and replaces them with wrapper elements that can be enhanced client-side
 * using fountain-js for screenplay formatting.
 * 
 * Similar to rehype-abc and rehype-mermaid, this plugin:
 * - Processes server-side for better performance and SEO
 * - Creates semantic wrapper elements with data attributes
 * - Preserves source code in collapsible details elements
 * - Enables client-side enhancement while maintaining SSR benefits
 */

import { visit } from 'unist-util-visit'
import type { Element, Root } from 'hast'
import type { Plugin } from 'unified'
import { MAX_CODE_LENGTH, createErrorElement } from './security-constants'

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface FountainOptions {
  // Future configuration options for Fountain rendering
  // For now, we'll use fountain-js defaults
}

// Generate a unique ID for each Fountain screenplay
const generateFountainId = (): string => {
  return 'fountain-screenplay-' + Math.random().toString(36).substr(2, 9)
}

const rehypeFountain: Plugin<[FountainOptions?], Root> = (options = {}) => { // eslint-disable-line @typescript-eslint/no-unused-vars
  return (tree: Root) => {
    visit(tree, 'element', (node: Element, index: number | undefined, parent: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
      // Look for code blocks with language-fountain class
      if (
        node.tagName === 'pre' &&
        node.children.length === 1 &&
        node.children[0].type === 'element' &&
        node.children[0].tagName === 'code'
      ) {
        const codeElement = node.children[0] as Element
        const classNames = codeElement.properties?.className as string[] | undefined
        
        if (classNames?.includes('language-fountain')) {
          // Extract the Fountain screenplay code
          let fountainCode = ''
          visit(codeElement, 'text', (textNode: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
            fountainCode += textNode.value
          })

          const trimmedCode = fountainCode.trim()
          
          // Skip empty blocks
          if (!trimmedCode) return
          
          // Validate code length
          if (trimmedCode.length > MAX_CODE_LENGTH) {
            if (parent && typeof index === 'number') {
              parent.children[index] = createErrorElement(
                'Fountain screenplay code exceeds maximum allowed length.',
                'fountain-screenplay-error'
              )
            }
            return
          }

          // Generate unique ID for this screenplay
          const fountainId = generateFountainId()

          // Create wrapper with data attributes for client-side processing
          const wrapper: Element = {
            type: 'element',
            tagName: 'div',
            properties: {
              className: ['fountain-screenplay-wrapper'],
              dataFountainCode: fountainCode,
              dataFountainId: fountainId
            },
            children: [
              // Container for the rendered screenplay
              {
                type: 'element',
                tagName: 'div',
                properties: {
                  id: fountainId,
                  className: ['fountain-screenplay-container']
                },
                children: []
              },
              // Collapsible source code display
              {
                type: 'element',
                tagName: 'details',
                properties: {
                  className: ['fountain-screenplay-source']
                },
                children: [
                  {
                    type: 'element',
                    tagName: 'summary',
                    properties: {
                      className: ['text-sm', 'text-gray-600', 'cursor-pointer']
                    },
                    children: [
                      { type: 'text', value: 'Show Fountain screenplay source' }
                    ]
                  },
                  {
                    type: 'element',
                    tagName: 'pre',
                    properties: {
                      className: ['mt-2', 'p-2', 'rounded', 'text-sm', 'overflow-auto']
                    },
                    children: [
                      {
                        type: 'element',
                        tagName: 'code',
                        properties: {},
                        children: [
                          { type: 'text', value: fountainCode }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }

          // Replace the code block with our wrapper
          if (parent && typeof index === 'number') {
            parent.children[index] = wrapper
          }
        }
      }
    })
  }
}

export default rehypeFountain