"use strict";
/**
 * @file pattern-exporter.ts
 * Export LLM UI patterns to Drupal UI Suite format
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PatternExporter = void 0;
const pattern_registry_1 = require("../patterns/pattern-registry");
const drupal_adapter_1 = require("../adapters/drupal-adapter");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
/**
 * Pattern Exporter for Drupal UI Suite integration
 */
class PatternExporter {
    /**
     * Export all patterns to Drupal format
     */
    static async exportAll(options) {
        console.log('🚀 Exporting LLM UI patterns to Drupal UI Suite format...');
        // Create output directories
        this.createDirectories(options.outputDir);
        // Export each pattern
        for (const [patternId, pattern] of Object.entries(pattern_registry_1.patternRegistry)) {
            await this.exportPattern(pattern, options);
        }
        // Generate index file
        await this.generateIndexFile(options.outputDir);
        console.log('✅ Export complete!');
    }
    /**
     * Export a single pattern
     */
    static async exportPattern(pattern, options) {
        const patternDir = path.join(options.outputDir, pattern.id);
        // Create pattern directory
        if (!fs.existsSync(patternDir)) {
            fs.mkdirSync(patternDir, { recursive: true });
        }
        // Generate YAML definition
        const yamlContent = drupal_adapter_1.DrupalAdapter.generateYamlPattern(pattern);
        const yamlPath = path.join(patternDir, `${pattern.id}.ui_patterns.yml`);
        fs.writeFileSync(yamlPath, yamlContent);
        console.log(`  ✓ Generated ${pattern.id}.ui_patterns.yml`);
        // Generate Twig template
        if (options.generateTemplates) {
            const twigContent = drupal_adapter_1.DrupalAdapter.generateTwigTemplate(pattern);
            const twigPath = path.join(patternDir, `pattern-${pattern.id}.html.twig`);
            fs.writeFileSync(twigPath, twigContent);
            console.log(`  ✓ Generated pattern-${pattern.id}.html.twig`);
        }
        // Generate CSS file
        if (options.generateStyles) {
            const cssContent = this.generatePatternStyles(pattern);
            const cssPath = path.join(patternDir, `${pattern.id}.css`);
            fs.writeFileSync(cssPath, cssContent);
            console.log(`  ✓ Generated ${pattern.id}.css`);
        }
        // Generate pattern documentation
        if (options.generateDocs) {
            const docContent = this.generatePatternDocumentation(pattern);
            const docPath = path.join(patternDir, `README.md`);
            fs.writeFileSync(docPath, docContent);
            console.log(`  ✓ Generated README.md for ${pattern.id}`);
        }
        // Generate JavaScript integration
        const jsContent = this.generateJavaScriptIntegration(pattern);
        const jsPath = path.join(patternDir, `${pattern.id}.js`);
        fs.writeFileSync(jsPath, jsContent);
        console.log(`  ✓ Generated ${pattern.id}.js`);
    }
    /**
     * Create necessary directories
     */
    static createDirectories(outputDir) {
        const dirs = [
            outputDir,
            path.join(outputDir, '_generated'),
            path.join(outputDir, '_docs'),
        ];
        dirs.forEach(dir => {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        });
    }
    /**
     * Generate pattern styles
     */
    static generatePatternStyles(pattern) {
        const className = `.llm-ui-${pattern.id.replace(/_/g, '-')}`;
        let css = `/**
 * Styles for ${pattern.label}
 * Auto-generated from LLM UI pattern definition
 */

${className} {
  /* Base styles */
  position: relative;
  display: block;
  
  /* AI enhancement indicator */
  &[data-ai-enabled="true"] {
    &::before {
      content: "✨";
      position: absolute;
      top: 0.25rem;
      right: 0.25rem;
      font-size: 0.75rem;
      opacity: 0.6;
    }
  }
}

${className}__title {
  margin: 0 0 1rem;
  font-size: 1.25rem;
  font-weight: 600;
}

${className}__content {
  margin: 0;
}
`;
        // Add variant styles
        if (pattern.fields.variant?.options) {
            css += `\n/* Variant styles */\n`;
            Object.keys(pattern.fields.variant.options).forEach(variant => {
                css += `
${className}--${variant} {
  /* ${variant} variant styles */
}
`;
            });
        }
        // Add AI feature styles
        if (pattern.aiFeatures) {
            css += `\n/* AI feature indicators */\n`;
            pattern.aiFeatures.forEach(feature => {
                css += `
${className}[data-ai-${feature.id.replace(/_/g, '-')}="true"] {
  /* Styles when ${feature.label} is active */
}
`;
            });
        }
        return css;
    }
    /**
     * Generate JavaScript integration
     */
    static generateJavaScriptIntegration(pattern) {
        return `/**
 * JavaScript integration for ${pattern.label}
 * Bridges Drupal with React component
 */

(function (Drupal, once) {
  'use strict';

  Drupal.behaviors.llmUi${this.toPascalCase(pattern.id)} = {
    attach: function (context, settings) {
      const elements = once('llm-ui-${pattern.id}', '.llm-ui-${pattern.id.replace(/_/g, '-')}', context);
      
      elements.forEach(function (element) {
        // Initialize AI features
        const aiConfig = element.querySelector('.ai-config');
        if (aiConfig) {
          const config = JSON.parse(aiConfig.textContent);
          initializeAIFeatures(element, config);
        }

        // Bridge to React component
        if (window.LLMUIComponents && window.LLMUIComponents.${this.toPascalCase(pattern.id)}) {
          const props = extractPropsFromElement(element);
          window.LLMUIComponents.mount${this.toPascalCase(pattern.id)}(element, props);
        }
      });
    }
  };

  /**
   * Initialize AI features for the component
   */
  function initializeAIFeatures(element, config) {
    ${pattern.aiFeatures ? pattern.aiFeatures.map(feature => `
    // Initialize ${feature.label}
    if (config.${feature.id} && element.dataset.ai${this.toPascalCase(feature.id)} === 'true') {
      console.log('Initializing ${feature.label} for', element);
      // AI feature initialization code here
    }`).join('\n') : '// No AI features to initialize'}
  }

  /**
   * Extract props from DOM element
   */
  function extractPropsFromElement(element) {
    const props = {};
    
    // Extract data attributes
    Object.keys(element.dataset).forEach(key => {
      if (key.startsWith('prop')) {
        const propName = key.replace('prop', '').toLowerCase();
        props[propName] = element.dataset[key];
      }
    });

    // Extract content
    ${Object.entries(pattern.fields).map(([key, field]) => {
            if (field.type === 'text' && key !== 'content') {
                return `props.${key} = element.querySelector('.${pattern.id.replace(/_/g, '-')}__${key}')?.textContent;`;
            }
            return '';
        }).filter(Boolean).join('\n    ')}

    return props;
  }

})(Drupal, once);`;
    }
    /**
     * Generate pattern documentation
     */
    static generatePatternDocumentation(pattern) {
        let doc = `# ${pattern.label}\n\n`;
        doc += `${pattern.description}\n\n`;
        doc += `## Usage\n\n`;
        doc += '```twig\n';
        doc += `{% include '@patterns/${pattern.id}/pattern-${pattern.id}.html.twig' with {\n`;
        Object.entries(pattern.fields).forEach(([key, field]) => {
            if (field.type !== 'mapping') {
                doc += `  ${key}: '${field.default || `Example ${field.label}`}',\n`;
            }
        });
        doc += `} %}\n`;
        doc += '```\n\n';
        if (pattern.aiFeatures && pattern.aiFeatures.length > 0) {
            doc += `## AI Features\n\n`;
            pattern.aiFeatures.forEach(feature => {
                doc += `### ${feature.label}\n`;
                doc += `${feature.description}\n\n`;
            });
        }
        doc += `## Fields\n\n`;
        Object.entries(pattern.fields).forEach(([key, field]) => {
            doc += `### ${key}\n`;
            doc += `- **Type**: ${field.type}\n`;
            doc += `- **Label**: ${field.label}\n`;
            if (field.description) {
                doc += `- **Description**: ${field.description}\n`;
            }
            if (field.required) {
                doc += `- **Required**: Yes\n`;
            }
            if (field.options) {
                doc += `- **Options**: ${Object.values(field.options).join(', ')}\n`;
            }
            doc += '\n';
        });
        return doc;
    }
    /**
     * Generate index file
     */
    static async generateIndexFile(outputDir) {
        let content = '# LLM UI Patterns for Drupal\n\n';
        content += 'This directory contains auto-generated Drupal UI patterns from LLM UI components.\n\n';
        content += '## Available Patterns\n\n';
        const categories = new Map();
        // Group patterns by category
        Object.values(pattern_registry_1.patternRegistry).forEach(pattern => {
            const category = pattern.category;
            if (!categories.has(category)) {
                categories.set(category, []);
            }
            categories.get(category).push(pattern);
        });
        // Generate content for each category
        categories.forEach((patterns, category) => {
            content += `### ${this.formatCategory(category)}\n\n`;
            patterns.forEach(pattern => {
                content += `- **${pattern.label}** (\`${pattern.id}\`): ${pattern.description}\n`;
            });
            content += '\n';
        });
        content += '## Integration\n\n';
        content += 'To use these patterns in your Drupal theme:\n\n';
        content += '1. Copy this directory to your theme\'s `patterns` folder\n';
        content += '2. Clear Drupal cache\n';
        content += '3. Patterns will be available in UI Patterns module\n\n';
        content += '## AI Features\n\n';
        content += 'Many patterns include AI-powered features that require:\n';
        content += '- `llm_platform_manager/ai-engine` library\n';
        content += '- Proper API key configuration\n';
        content += '- Enabled AI modules\n';
        const indexPath = path.join(outputDir, 'README.md');
        fs.writeFileSync(indexPath, content);
    }
    /**
     * Convert string to PascalCase
     */
    static toPascalCase(str) {
        return str
            .split('_')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join('');
    }
    /**
     * Format category name
     */
    static formatCategory(category) {
        const categoryNames = {
            'ai-enhanced': 'AI-Enhanced Components',
            'layout': 'Layout Components',
            'form': 'Form Components',
            'display': 'Display Components',
        };
        return categoryNames[category] || category;
    }
}
exports.PatternExporter = PatternExporter;
//# sourceMappingURL=pattern-exporter.js.map