name: "CMS Structure Generation"
description: "Generate CMS structure for components and integrate with example_blocks.json"
version: "1.0.0"

metadata:
  category: "convert"
  complexity: "medium"
  estimated_time: "3-5 minutes"
  prerequisites:
    - "Component Twig template must exist"
    - "Component must be added to example_blocks.twig"

variables:
  component_name: "{component_name}"
  template_path: "{template_path}"

steps:
  # Step 1: Validate Component Exists
  - id: "validate-component-exists"
    name: "Validate Component Template Exists"
    type: "validation"
    required: true
    validation:
      checks:
        - pattern: "^sites/default/templates/includes/(page_blocks|elements|partials)/([^/]+)\\.twig$"
          value: "{template_path}"
          error_message: "Template must be in page_blocks/, elements/, or partials/ directory"
        - file: "{template_path}"
          exists: true
          error_message: "Component template not found: {template_path}"
      on_failure:
        action: "stop"
        message: |
          ❌ Component template not found.

          Usage: /mtc-cms-structure <component-name>

          The component Twig template must exist in one of:
          - sites/default/templates/includes/page_blocks/
          - sites/default/templates/includes/elements/
          - sites/default/templates/includes/partials/

  # Step 2: Extract Component Name and Metadata
  - id: "extract-component-metadata"
    name: "Extract Component Name and Classification"
    type: "workflow"
    depends_on: ["validate-component-exists"]
    workflow:
      track_with_todo: true
      actions:
        - "Parse component name from template path"
        - "Determine template directory (page_blocks/elements/partials)"
        - "Extract component classification for CMS structure"
        - "Set variables for subsequent steps"

  # Step 3: Analyze Twig Template Structure
  - id: "analyze-twig-template"
    name: "Analyze Twig Template Structure"
    type: "workflow"
    depends_on: ["extract-component-metadata"]
    workflow:
      track_with_todo: true
      actions:
        - "Read Twig template file"
        - "Extract all variables ({{ variable_name }})"
        - "Detect array/loop structures ({% for item in items %})"
        - "Identify optional variables ({% if variable %})"
        - "Extract documentation comments for context"
        - "Analyze variable usage patterns"

  # Step 4: AI-Powered Field Type Inference
  - id: "infer-field-types"
    name: "Infer CMS Field Types Using AI"
    type: "workflow"
    depends_on: ["analyze-twig-template"]
    workflow:
      track_with_todo: true
      inference_patterns:
        text_fields:
          - "*_title, title → text"
          - "*_name, name → text"
          - "*_link, *_url, link, url → text"
          - "button_text, cta_text → text"

        textarea_fields:
          - "*_content, content → textarea (simpleTinymce)"
          - "*_description, description → textarea (simpleTinymce)"
          - "intro_* → textarea (simpleTinymce)"

        checkbox_fields:
          - "show_*, is_*, has_*, enable_* → checkbox"
          - "dark_*, light_* → checkbox"

        image_fields:
          - "*_image, *_photo, *_banner, background_image → image"
          - "logo, icon_image → image"

        select_fields:
          - "*_icon (with svg context) → select (svgicons.php)"

        array_fields:
          - "stats[], items[], cards[], features[] → allow_more section"

      actions:
        - "Apply inference patterns to extracted variables"
        - "Use AI to determine ambiguous field types"
        - "Identify nested/repeatable structures"
        - "Generate field order based on template flow"

  # Step 5: Detect Repeatable Sections
  - id: "detect-repeatable-sections"
    name: "Analyze Array Structures for Repeatable Blocks"
    type: "workflow"
    depends_on: ["infer-field-types"]
    workflow:
      track_with_todo: true
      actions:
        - "Detect {% for %} loops in template"
        - "Extract array variable names"
        - "Analyze nested structure of array items"
        - "Determine appropriate allow_more_max value"
        - "Create separate CMS block for each array"

  # Step 6: Generate CMS JSON Structure
  - id: "generate-cms-json"
    name: "Generate CMS Structure JSON"
    type: "workflow"
    depends_on: ["detect-repeatable-sections"]
    workflow:
      track_with_todo: true
      actions:
        - "Get next available order number from example_blocks.json"
        - "Generate main component block structure"
        - "Generate repeatable blocks (if arrays detected)"
        - "Add appropriate field settings (image crop, css_class, etc.)"
        - "CRITICAL: Use 'original' size for image fields (safest default)"
        - "Format JSON with proper indentation"

      image_field_settings:
        - "ALWAYS use: {\"image_sizes\":[\"original\"]}"
        - "Reason: 'original' size always exists in cms/includes/image_folders.php"
        - "Avoids 404 errors from undefined image sizes"
        - "Admin can create custom sizes later if needed"
        - "DO NOT use: crop_adjust or custom size names unless explicitly requested"

      json_structure_template: |
        {
            "name": "{Component Display Name}",
            "order": "{next_order}",
            "items": [{
                "order": "0",
                "data": [
                    {field definitions}
                ]
            }]
        }

      repeatable_structure_template: |
        {
            "name": "{Component Display Name} {Array Name}",
            "order": "{next_order}",
            "allow_more": "1",
            "allow_more_max": "{inferred_max}",
            "items": [{
                "order": "0",
                "data": [
                    {nested field definitions}
                ]
            }]
        }

  # Step 7: Preview and Approval Gate
  - id: "preview-cms-structure"
    name: "Preview Generated CMS Structure"
    type: "approval_gate"
    depends_on: ["generate-cms-json"]
    required: true
    approval_gate:
      required_keywords: ["approved", "looks good", "proceed", "yes"]
      approval_message: |
        📋 **Generated CMS Structure Preview**

        The following structure will be added to example_blocks.json:

        {preview_json}

        **Detected Fields:**
        {field_summary}

        **Repeatable Sections:**
        {array_summary}

        To proceed, respond with: "approved", "looks good", "proceed", or "yes"
        To cancel, respond with: "cancel" or "no"
      timeout_hours: 24

  # Step 8: Backup example_blocks.json
  - id: "backup-cms-config"
    name: "Backup Current CMS Configuration"
    type: "workflow"
    depends_on: ["preview-cms-structure"]
    workflow:
      track_with_todo: true
      actions:
        - "Create backup: sites/default/templates/structures/example_blocks.json.backup"
        - "If .backup exists, create .backup.{timestamp}"
        - "Log backup location"

  # Step 9: Insert into example_blocks.json
  - id: "insert-cms-structure"
    name: "Insert Structure into example_blocks.json"
    type: "workflow"
    depends_on: ["backup-cms-config"]
    workflow:
      track_with_todo: true
      actions:
        - "Read current example_blocks.json"
        - "Parse JSON structure"
        - "Insert new blocks at correct order position"
        - "Maintain proper JSON formatting"
        - "Write updated JSON back to file"

  # Step 10: Validate JSON Syntax
  - id: "validate-json-syntax"
    name: "Validate JSON Syntax"
    type: "validation"
    depends_on: ["insert-cms-structure"]
    validation:
      checks:
        - file: "sites/default/templates/structures/example_blocks.json"
          exists: true
          error_message: "example_blocks.json file missing after update"
      on_failure:
        action: "stop"
        message: |
          ❌ JSON validation failed.
          Restoring backup from: {backup_path}

  # Step 11: Update example_blocks.twig Include
  - id: "update-example-blocks-include"
    name: "Update example_blocks.twig with CMS Data Mapping"
    type: "workflow"
    depends_on: ["validate-json-syntax"]
    workflow:
      track_with_todo: true
      actions:
        - "Locate existing component include in example_blocks.twig"
        - "CRITICAL: REMOVE 'show_dummy_data: true' from the include parameters"
        - "Generate CMS data mapping for all fields"
        - "Replace the entire include block with CMS-mapped version"
        - "Apply |raw filter to textarea (TinyMCE) fields in the mapping"
        - "Use correct array access pattern for repeatable sections"
        - "Preserve existing classes and options (except show_dummy_data)"
        - "Validate Twig syntax"

      critical_rule: |
        IMPORTANT: The 'show_dummy_data: true' parameter MUST be REMOVED when adding CMS mappings.
        Dummy data should ONLY be visible at: /component/preview/page_blocks/{component}.twig
        On example_blocks.twig and all other pages, data comes exclusively from CMS.

      before_example: |
        {# BEFORE (from /mtc-extract): #}
        {% include 'includes/page_blocks/component_name.twig' with {
            show_dummy_data: true
        }%}

      after_example: |
        {# AFTER (from /mtc-cms-structure): #}
        {% include 'includes/page_blocks/component_name.twig' with {
            title: p.pagedata['Component Name'][0]['Title']['value'],
            description: p.pagedata['Component Name'][0]['Description']['value'],
            items: p.pagedata['Component Name Items']
        }%}

      twig_mapping_template: |
        {% include 'includes/{template_directory}/{component_name}.twig' with {
            {generated_cms_mappings}
        }%}

      cms_mapping_pattern: |
        'field_name': p.pagedata['Block Name'][0]['Field Name']['value']

      cms_mapping_rules:
        single_fields:
          - pattern: "p.pagedata['Block Name'][0]['Field Name']['value']"
          - textarea_fields: "Add |raw filter for TinyMCE content"
          - text_fields: "No filter needed"
          - image_fields: "No filter needed"

        array_fields:
          - pattern: "p.pagedata['Block Name Array']"
          - access_in_loop: "item['Field Name']['value']"
          - note: "DO NOT use [0] for array pagedata - pass the entire array"

  # Step 12: Validate Integration
  - id: "validate-cms-integration"
    name: "Validate CMS Integration"
    type: "validation"
    depends_on: ["update-example-blocks-include"]
    validation:
      checks:
        - file: "sites/default/templates/structures/example_blocks.json"
          contains: ["\"name\": \"{component_display_name}\""]
          error_message: "Component structure not found in example_blocks.json"
        - file: "sites/default/templates/pages/example_blocks.twig"
          contains: ["p.pagedata['{component_display_name}']"]
          error_message: "CMS data mapping not added to example_blocks.twig"
      on_failure:
        action: "stop"
        message: "❌ CMS integration validation failed."

  # Step 13: Create Documentation
  - id: "create-cms-documentation"
    name: "Document CMS Structure Addition"
    type: "workflow"
    depends_on: ["validate-cms-integration"]
    workflow:
      track_with_todo: true
      actions:
        - "Append to .frontend/components/{component_name}.md"
        - "Document CMS block structure"
        - "List all CMS fields with types"
        - "Show example usage in example_blocks.twig"
        - "Record order numbers used"

      documentation_template: |
        ## CMS Integration

        ### CMS Blocks Added

        **Block 1: {component_name}** (Order: {order})
        - Field 1: {field_name} ({field_type})
        - Field 2: ...

        **Block 2: {component_name} {array_name}** (Order: {order})
        - Repeatable: Yes (max: {max})
        - Field 1: ...

        ### Example Usage

        ```twig
        {% include 'includes/{dir}/{component_name}.twig' with {
            {example_mapping}
        }%}
        ```

        ### CMS Path

        Edit content at: `sites/default/templates/structures/example_blocks.json`
        View on page: `sites/default/templates/pages/example_blocks.twig`

workflow_completion:
  success_message: |
    🎉 **CMS Structure Generation Complete!**

    ✅ **Added to example_blocks.json:**
    - {component_display_name} (Order: {order})
    {additional_blocks}

    ✅ **Updated Files:**
    - `sites/default/templates/structures/example_blocks.json`
    - `sites/default/templates/pages/example_blocks.twig`
    - `.frontend/components/{component_name}.md`

    ✅ **Backup Created:**
    - `{backup_path}`

    ✅ **CMS Fields Generated:**
    {field_list}

    🚀 **Next Steps:**
    1. Test the component in the CMS admin panel
    2. Add sample data via CMS
    3. View results on example_blocks page

    📁 **CMS Admin Path:** /cms/admin/content_manager/
    📄 **Example Page:** /example-blocks

  failure_message: |
    ❌ **CMS Structure Generation Failed**

    Please check the error messages above.

    **Backup Location:** {backup_path}

    Common issues:
    - Invalid template path
    - JSON syntax errors
    - Component not added to example_blocks.twig

    You can retry with: `/mtc-cms-structure {component_name}`

validation_rules:
  - component_exists: true
  - json_syntax_valid: true
  - cms_integration_complete: true
  - documentation_updated: true

# AI Execution Instructions
executor_instructions:
  field_type_inference:
    - "Use variable name patterns first"
    - "Consider template context (image paths, URLs, etc.)"
    - "Default to 'text' for ambiguous cases"
    - "Always add simpleTinymce to textarea fields"
    - "CRITICAL: For image fields, ALWAYS use: {\"image_sizes\":[\"original\"]}"
    - "DO NOT generate custom image size names (e.g., results_bg, component_image)"
    - "Reason: Only 'original' size is guaranteed to exist"

  repeatable_sections:
    - "Any {% for item in items %} loop = allow_more block"
    - "Infer max from design context (3-6 for stats, 10+ for FAQs)"
    - "Create separate block with '{Component} {Array Name}' naming"

  json_formatting:
    - "Use 4-space indentation"
    - "Maintain consistent structure with existing blocks"
    - "Escape special characters in regex patterns"
    - "Use double quotes for all strings"

  cms_mapping:
    - "CRITICAL: Add |raw filter to ALL textarea (TinyMCE) fields"
    - "Pattern for single fields: p.pagedata['Block Name'][0]['Field Name']['value']"
    - "Pattern for array fields: p.pagedata['Block Name Array'] (NO [0])"
    - "In loops, access array items: item['Field Name']['value']"
    - "Preserve existing class/option parameters"
    - "Add comments for complex mappings"

  twig_template_updates:
    - "CRITICAL: Update component Twig templates to handle CMS data correctly"
    - "For textarea fields: Add |raw filter (e.g., {{ description|raw }})"
    - "CRITICAL: TinyMCE fields MUST use <div> wrappers, NEVER <p> tags"
    - "Reason: TinyMCE auto-wraps in <p>, using <p> wrapper creates nested invalid HTML"
    - "Correct: <div class='component__description'>{{ description|raw }}</div>"
    - "Wrong: <p class='component__description'>{{ description|raw }}</p>"
    - "For array access in loops: Use item['Field Name']['value'] pattern"
    - "Example: {% for stat in stats %} {{ stat['Number']['value'] }} {% endfor %}"
    - "Do NOT use stat.number - use stat['Number']['value'] for CMS data"
    - "CRITICAL: For images, use image_folders global variable pattern"
    - "Pattern: {% set image_folder_path = image_folders['cms_images']['original']['path'] %}"
    - "Then: <img src='/{{ image_folder_path }}/{{ image_variable }}' />"
    - "Result: /uploads/images/cms/original/filename.jpg"

  array_loop_dual_format:
    description: |
      Component templates must support BOTH dummy data format AND CMS data format.
      This allows the component to work in preview mode (dummy data) and production (CMS data).

    pattern: |
      {% for item in items %}
          {# Support both dummy data format (item.field.value) and CMS format (item['Field']['value']) #}
          {% set item_name = item['Name']['value'] is defined ? item['Name']['value'] : item.Name.value %}
          {% set item_role = item['Role']['value'] is defined ? item['Role']['value'] : item.Role.value %}
          {% set item_image = item['Image']['value'] is defined ? item['Image']['value'] : item.Image.value %}

          {# Handle CMS image paths - add image_folders prefix for non-URL images #}
          {% if item_image is not empty and item_image starts with 'http' == false and image_folders is defined %}
              {% set item_image = '/' ~ image_folders['cms_images']['original']['path'] ~ '/' ~ item_image %}
          {% endif %}

          {# Use the normalized variables in your HTML #}
          <div class="item">
              <img src="{{ item_image }}" alt="{{ item_name }}">
              <h3>{{ item_name }}</h3>
              <p>{{ item_role }}</p>
          </div>
      {% endfor %}

    rules:
      - "For each field in the loop, create a {% set %} that checks both formats"
      - "CMS format: item['Field Name']['value'] (with spaces, title case)"
      - "Dummy format: item.field_name.value (dot notation, snake_case)"
      - "Image fields need additional handling for CMS paths vs URLs"
      - "This dual-format approach ensures component works in both preview and production"

  tinymce_wrapper_rules:
    - "Fields with type='textarea' and css_class='simpleTinymce' or 'tinymce' = TinyMCE field"
    - "TinyMCE outputs: <p>Content here</p>, <ul><li>...</li></ul>, etc."
    - "Always use <div> wrapper for TinyMCE content to avoid nested <p> tags"
    - "Apply this rule to: *_content, *_description, *_disclaimer, any textarea field"
    - "Exception: If field is meant for inline text only (not rich text), <p> is OK"
