"use strict";
/**
 * @file drupal-adapter.ts
 * Drupal Adapter for LLM UI Components
 *
 * Bridges React components with Drupal's UI Suite modules
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.DrupalAdapter = void 0;
/**
 * Adapter class for converting LLM UI components to Drupal patterns
 */
class DrupalAdapter {
    /**
     * Convert a component pattern to Drupal UI Pattern format
     */
    static toDrupalPattern(pattern) {
        return {
            label: pattern.label,
            description: pattern.description,
            category: this.mapCategory(pattern.category),
            use: `@llm_ui/${pattern.id}`,
            fields: this.convertFields(pattern.fields),
            settings: this.generateSettings(pattern),
            libraries: this.getRequiredLibraries(pattern),
        };
    }
    /**
     * Convert pattern fields to Drupal format
     */
    static convertFields(fields) {
        const drupalFields = {};
        Object.entries(fields).forEach(([key, field]) => {
            drupalFields[key] = {
                type: this.mapFieldType(field.type),
                label: field.label,
                description: field.description,
                preview: field.default,
                required: field.required || false,
            };
            // Handle select fields
            if (field.type === 'select' && field.options) {
                drupalFields[key].options = field.options;
            }
            // Handle mapping fields (nested fields)
            if (field.type === 'mapping' && field.fields) {
                drupalFields[key].fields = this.convertFields(field.fields);
            }
        });
        return drupalFields;
    }
    /**
     * Map component categories to Drupal UI Suite categories
     */
    static mapCategory(category) {
        const categoryMap = {
            'ai-enhanced': 'AI Components',
            'layout': 'Layout',
            'form': 'Form Elements',
            'display': 'Display',
        };
        return categoryMap[category] || 'Other';
    }
    /**
     * Map field types to Drupal field types
     */
    static mapFieldType(type) {
        const typeMap = {
            'text': 'text',
            'boolean': 'boolean',
            'select': 'select',
            'number': 'number',
            'mapping': 'mapping',
        };
        return typeMap[type] || 'text';
    }
    /**
     * Generate settings for the pattern
     */
    static generateSettings(pattern) {
        const settings = {};
        // Add AI feature settings
        if (pattern.aiFeatures && pattern.aiFeatures.length > 0) {
            settings.ai_features = pattern.aiFeatures.map(feature => ({
                id: feature.id,
                label: feature.label,
                enabled: true,
                configurable: feature.configurable,
            }));
        }
        return settings;
    }
    /**
     * Get required Drupal libraries for the pattern
     */
    static getRequiredLibraries(pattern) {
        const libraries = [
            'llm_platform_manager/global',
            'llm_platform_manager/bfui',
        ];
        // Add AI-specific libraries
        if (pattern.aiFeatures && pattern.aiFeatures.length > 0) {
            libraries.push('llm_platform_manager/ai-engine');
            libraries.push('llm_platform_manager/machine-learning');
        }
        // Add category-specific libraries
        switch (pattern.category) {
            case 'form':
                libraries.push('core/drupal.form');
                break;
            case 'display':
                libraries.push('llm_platform_manager/analytics');
                break;
        }
        return libraries;
    }
    /**
     * Generate Twig template for a pattern
     */
    static generateTwigTemplate(pattern) {
        const className = `llm-ui-${pattern.id.replace(/_/g, '-')}`;
        let template = `{#
/**
 * @file
 * Template for ${pattern.label}
 *
 * Available variables:`;
        // Document available variables
        Object.entries(pattern.fields).forEach(([key, field]) => {
            template += `\n * - ${key}: ${field.label}`;
        });
        template += `\n * - attributes: HTML attributes for the component
 * - modifier_class: Additional CSS classes
 */
#}

{% set classes = [
  '${className}',
  modifier_class ? '${className}--' ~ modifier_class,
] %}

<div{{ attributes.addClass(classes) }}`;
        // Add data attributes for AI features
        if (pattern.aiFeatures) {
            pattern.aiFeatures.forEach(feature => {
                template += `\n  data-ai-${feature.id.replace(/_/g, '-')}="true"`;
            });
        }
        template += `>`;
        // Generate basic template structure
        template += this.generateTemplateContent(pattern);
        template += `\n</div>`;
        return template;
    }
    /**
     * Generate template content based on pattern fields
     */
    static generateTemplateContent(pattern) {
        let content = '';
        Object.entries(pattern.fields).forEach(([key, field]) => {
            if (field.type === 'mapping') {
                // Skip complex mappings in basic template
                return;
            }
            if (key === 'title') {
                content += `\n  {% if ${key} %}
    <h3 class="${pattern.id.replace(/_/g, '-')}__title">{{ ${key} }}</h3>
  {% endif %}`;
            }
            else if (key === 'content') {
                content += `\n  {% if ${key} %}
    <div class="${pattern.id.replace(/_/g, '-')}__content">{{ ${key} }}</div>
  {% endif %}`;
            }
        });
        // Add AI feature initialization
        if (pattern.aiFeatures) {
            content += `\n  {{ attach_library('llm_platform_manager/ai-engine') }}
  <script type="application/json" class="ai-config">{{ ai_config|json_encode|raw }}</script>`;
        }
        return content;
    }
    /**
     * Create props mapping for React component integration
     */
    static createPropsMapping(pattern) {
        const mappings = [];
        Object.entries(pattern.fields).forEach(([key, field]) => {
            if (field.type === 'mapping' && field.fields) {
                // Handle nested fields
                Object.entries(field.fields).forEach(([subKey, subField]) => {
                    mappings.push({
                        source: `${key}.${subKey}`,
                        target: `${key}${this.capitalize(subKey)}`,
                        transform: this.getFieldTransform(subField.type),
                    });
                });
            }
            else {
                mappings.push({
                    source: key,
                    target: key,
                    transform: this.getFieldTransform(field.type),
                });
            }
        });
        return mappings;
    }
    /**
     * Get field transformation function
     */
    static getFieldTransform(type) {
        switch (type) {
            case 'boolean':
                return (value) => value === 'true' || value === true || value === 1;
            case 'number':
                return (value) => Number(value);
            default:
                return undefined;
        }
    }
    /**
     * Capitalize first letter
     */
    static capitalize(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
    /**
     * Generate YAML pattern file content
     */
    static generateYamlPattern(pattern) {
        const drupalPattern = this.toDrupalPattern(pattern);
        let yaml = `${pattern.id}:\n`;
        yaml += `  label: '${drupalPattern.label}'\n`;
        if (drupalPattern.description) {
            yaml += `  description: '${drupalPattern.description}'\n`;
        }
        yaml += `  category: '${drupalPattern.category}'\n`;
        // Add fields
        yaml += `  fields:\n`;
        Object.entries(drupalPattern.fields).forEach(([key, field]) => {
            yaml += `    ${key}:\n`;
            yaml += `      type: ${field.type}\n`;
            yaml += `      label: '${field.label}'\n`;
            if (field.description) {
                yaml += `      description: '${field.description}'\n`;
            }
            if (field.preview !== undefined) {
                yaml += `      preview: ${typeof field.preview === 'string' ? `'${field.preview}'` : field.preview}\n`;
            }
            if (field.options) {
                yaml += `      options:\n`;
                Object.entries(field.options).forEach(([optKey, optValue]) => {
                    yaml += `        ${optKey}: '${optValue}'\n`;
                });
            }
        });
        // Add settings
        if (drupalPattern.settings && Object.keys(drupalPattern.settings).length > 0) {
            yaml += `  settings:\n`;
            if (drupalPattern.settings.ai_features) {
                yaml += `    ai_features:\n`;
                drupalPattern.settings.ai_features.forEach((feature) => {
                    yaml += `      - id: ${feature.id}\n`;
                    yaml += `        label: '${feature.label}'\n`;
                    yaml += `        enabled: ${feature.enabled}\n`;
                    yaml += `        configurable: ${feature.configurable}\n`;
                });
            }
        }
        // Add libraries
        if (drupalPattern.libraries && drupalPattern.libraries.length > 0) {
            yaml += `  libraries:\n`;
            drupalPattern.libraries.forEach(lib => {
                yaml += `    - ${lib}\n`;
            });
        }
        return yaml;
    }
}
exports.DrupalAdapter = DrupalAdapter;
//# sourceMappingURL=drupal-adapter.js.map