<?php

/**
 * JCOGS Image Pro - Watermark Parameter Package
 * ==============================================
 * Sophisticated multi-field interface for watermark parameters
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://JCOGS.net/
 * @since      Parameter Package Implementation
 */

namespace JCOGSDesign\JCOGSImagePro\Service\ParameterPackages;

use JCOGSDesign\JCOGSImagePro\Service\ParameterPackages\AbstractParameterPackage;
use JCOGSDesign\JCOGSImagePro\Service\ParameterRegistry;

/**
 * Watermark Parameter Package
 * 
 * Provides a comprehensive form interface for the watermark parameter with 14 specialized fields
 * based on the official JCOGS Image documentation format:
 * watermark='watermark_src|min_width,min_height|opacity|position_horizontal,position_vertical|offset_x,offset_y|rotation'
 * 
 * Supports watermark image overlay with position control, opacity, rotation, and repeat patterns.
 */
class WatermarkParameterPackage extends AbstractParameterPackage
{
    /**
     * Get package identifier
     * 
     * @return string Unique package name identifier
     */
    public function getName(): string 
    {
        return 'watermark_parameter_package';
    }

    /**
     * Get the display label for this parameter package
     * 
     * @return string Human-readable package label
     */
    public function getLabel(): string
    {
        return 'Watermark Parameters';
    }

    /**
     * Get the description for this parameter package
     * 
     * @return string Package description for display purposes
     */
    public function getDescription(): string
    {
        return 'Comprehensive watermark overlay parameters with position control, opacity, rotation, and repeat patterns';
    }

    /**
     * Get the category for this parameter package
     * 
     * @return string Package category classification
     */
    public function getCategory(): string
    {
        return 'transformational';
    }

    /**
     * Get parameters handled by this package
     * 
     * @return array List of parameter names this package handles
     */
    public function getParameters(): array 
    {
        return ['watermark'];
    }

    /**
     * Normalize watermark parameter to positional format
     * 
     * Accepts both formats and returns consistent positional pipe-delimited format:
     * - Input (positional): "/path/logo.png|0,0|100|center,center|0,0|0" → Output: "/path/logo.png|0,0|100|center,center|0,0|0"
     * - Input (named): "watermark_src:/path/logo.png|watermark_opacity:100|..." → Output: "/path/logo.png|0,0|100|center,center|0,0|0"
     * 
     * This method is the bridge between template tags and watermark filters,
     * ensuring backward compatibility while supporting the new named attribute system.
     * 
     * @param string $watermark_parameter Watermark parameter string in either format
     * @return string Normalized positional pipe-delimited format
     */
    public function normalizeWatermarkParameter(string $watermark_parameter): string
    {
        if (empty($watermark_parameter)) {
            return '';
        }

        // Convert named format to positional if needed
        if ($this->isNamedAttributeFormat($watermark_parameter)) {
            return $this->convertNamedToPositionalFormat($watermark_parameter);
        }

        // Already in positional format
        return $watermark_parameter;
    }

    /**
     * Get validation definitions for watermark sub-parameters
     * 
     * This is the SINGLE SOURCE OF TRUTH for watermark parameter validation rules.
     * All validation (preset forms, CP forms, filter processing) should use these definitions.
     * 
     * Watermark parameter format: "src|min_width,min_height|opacity|position_h,position_v|offset_x,offset_y|rotation"
     * Example: "/path/logo.png|0,0|80|right,bottom|10,10|0"
     * 
     * @return array Map of sub-parameter names to validation configurations
     */
    public function getSubParameterDefinitions(): array
    {
        return [
            // Sub-parameter 1: Watermark source image
            'watermark_src' => [
                'label' => 'Watermark Image Source',
                'description' => 'Path to the watermark image file (local or remote URL)',
                'type' => 'text',
                'default_value' => '',
                'validator' => 'string',
                'validation_config' => [
                    'min_length' => 1,
                    'allow_empty' => false
                ],
                'required' => true,
                'placeholder' => '/media/watermarks/logo.png'
            ],

            // Sub-parameter 2a: Minimum width
            'watermark_min_width' => [
                'label' => 'Minimum Image Width',
                'description' => 'Minimum width the image must have for watermark to be applied',
                'type' => 'text',
                'default_value' => '0',
                'validator' => 'numeric',
                'validation_config' => [
                    'allow_negative' => false,
                    'allow_percentage' => true,
                    'allow_units' => ['px', '%'],
                    'min_value' => 0,
                    'default_unit' => 'px'
                ],
                'placeholder' => '300 or 25%'
            ],

            // Sub-parameter 2b: Minimum height
            'watermark_min_height' => [
                'label' => 'Minimum Image Height',
                'description' => 'Minimum height the image must have for watermark to be applied',
                'type' => 'text',
                'default_value' => '0',
                'validator' => 'numeric',
                'validation_config' => [
                    'allow_negative' => false,
                    'allow_percentage' => true,
                    'allow_units' => ['px', '%'],
                    'min_value' => 0,
                    'default_unit' => 'px'
                ],
                'placeholder' => '200 or 30%'
            ],

            // Sub-parameter 3: Opacity
            'watermark_opacity' => [
                'label' => 'Watermark Opacity',
                'description' => 'Transparency level of the watermark overlay (0-100)',
                'type' => 'text',
                'default_value' => '100',
                'validator' => 'percentage',
                'validation_config' => [
                    'min_value' => 0,
                    'max_value' => 100,
                    'format' => '0-100' // 0-100 range
                ],
                'placeholder' => '100 (opaque), 50 (semi-transparent)'
            ],

            // Sub-parameter 4a: Horizontal position
            'watermark_position_h' => [
                'label' => 'Horizontal Position',
                'description' => 'Horizontal placement of watermark',
                'type' => 'select',
                'default_value' => 'center',
                'validator' => 'enum',
                'validation_config' => [
                    'allowed_values' => ['left', 'center', 'right', 'repeat'],
                    'case_sensitive' => false
                ],
                'choices' => [
                    'left' => 'Left',
                    'center' => 'Center (default)',
                    'right' => 'Right',
                    'repeat' => 'Repeat (tiled pattern)'
                ]
            ],

            // Sub-parameter 4b: Vertical position
            'watermark_position_v' => [
                'label' => 'Vertical Position',
                'description' => 'Vertical placement of watermark',
                'type' => 'select',
                'default_value' => 'center',
                'validator' => 'enum',
                'validation_config' => [
                    'allowed_values' => ['top', 'center', 'bottom'],
                    'case_sensitive' => false
                ],
                'choices' => [
                    'top' => 'Top',
                    'center' => 'Center (default)',
                    'bottom' => 'Bottom'
                ]
            ],

            // Sub-parameter 5a: Horizontal offset
            'watermark_offset_x' => [
                'label' => 'Horizontal Offset',
                'description' => 'Fine-tune horizontal watermark position (pixels or percentage)',
                'type' => 'text',
                'default_value' => '0',
                'validator' => 'numeric',
                'validation_config' => [
                    'allow_negative' => true,
                    'allow_percentage' => true,
                    'allow_units' => ['px', '%'],
                    'default_unit' => 'px'
                ],
                'placeholder' => '0 or 10px or 5%'
            ],

            // Sub-parameter 5b: Vertical offset
            'watermark_offset_y' => [
                'label' => 'Vertical Offset',
                'description' => 'Fine-tune vertical watermark position (pixels or percentage)',
                'type' => 'text',
                'default_value' => '0',
                'validator' => 'numeric',
                'validation_config' => [
                    'allow_negative' => true,
                    'allow_percentage' => true,
                    'allow_units' => ['px', '%'],
                    'default_unit' => 'px'
                ],
                'placeholder' => '0 or -10px or -2%'
            ],

            // Sub-parameter 6: Rotation
            'watermark_rotation' => [
                'label' => 'Watermark Rotation',
                'description' => 'Rotation angle in degrees (anti-clockwise)',
                'type' => 'text',
                'default_value' => '0',
                'validator' => 'numeric',
                'validation_config' => [
                    'allow_negative' => true,
                    'allow_percentage' => false,
                    'min_value' => -360,
                    'max_value' => 360,
                    'default_unit' => ''
                ],
                'placeholder' => '0, 45, 90, -45'
            ]
        ];
    }

    /**
     * Get package priority for parameter package selection
     * 
     * Higher priority (lower number) packages are preferred for handling parameters.
     * Set to 22 to have higher priority than TransformationalParameterPackage (30).
     * 
     * @return int Priority level (lower = higher priority)
     */
    public function getPriority(): int
    {
        return 22; // Higher priority than TransformationalParameterPackage (30)
    }

    /**
     * Generate comprehensive form fields for watermark parameter
     * 
     * Creates 14 specialized fields for complete watermark control including
     * source image, positioning, opacity, rotation, and repeat patterns.
     * 
     * @param array $current_values Current parameter values for form population
     * @return array Form field definitions for EE CP Form Service
     */
    protected function getPackageFormFields(array $current_values = []): array
    {
        // Get current watermark value from current_values array
        $currentValue = $current_values['watermark'] ?? '';
        
        // Parse current watermark value into components using the composite parser
        $parsed = $this->parseCompositeString('watermark', $currentValue);
        
        return [
            // Watermark source image
            'watermark_src' => [
                'type' => 'text',
                'value' => $parsed['watermark_src'] ?? '',
                'label' => 'Watermark Image Source',
                'desc' => 'Path to the watermark image file (local or remote URL)',
                'example' => '/media/watermarks/logo.png or https://example.com/watermark.webp',
                'required' => true
            ],
            
            // Minimum dimensions
            'watermark_min_width' => [
                'type' => 'text',
                'value' => $parsed['watermark_min_width'] ?? '0',
                'label' => 'Minimum Image Width',
                'desc' => 'Minimum width the image must have for watermark to be applied',
                'example' => '300 (pixels) or 25% (percentage of image width)'
            ],
            
            'watermark_min_height' => [
                'type' => 'text',
                'value' => $parsed['watermark_min_height'] ?? '0',
                'label' => 'Minimum Image Height',
                'desc' => 'Minimum height the image must have for watermark to be applied',
                'example' => '200 (pixels) or 30% (percentage of image height)'
            ],
            
            // Opacity
            'watermark_opacity' => [
                'type' => 'text',
                'value' => $parsed['watermark_opacity'] ?? '100',
                'label' => 'Watermark Opacity',
                'desc' => 'Transparency level of the watermark overlay (0-100)',
                'example' => '100 (fully opaque), 50 (semi-transparent), 25 (mostly transparent)'
            ],
            
            // Position controls
            'watermark_position_h' => [
                'type' => 'select',
                'choices' => [
                    'left' => 'Left',
                    'center' => 'Center',
                    'right' => 'Right',
                    'repeat' => 'Repeat Pattern'
                ],
                'value' => $parsed['watermark_position_h'] ?? 'center',
                'label' => 'Horizontal Position',
                'desc' => 'Horizontal positioning of the watermark on the image',
                'example' => 'Choose "repeat" to create a tiled watermark pattern'
            ],
            
            'watermark_position_v' => [
                'type' => 'select',
                'choices' => [
                    'top' => 'Top',
                    'center' => 'Center',
                    'bottom' => 'Bottom'
                ],
                'value' => $parsed['watermark_position_v'] ?? 'center',
                'label' => 'Vertical Position',
                'desc' => 'Vertical positioning of the watermark on the image',
                'example' => '"bottom" for footer watermarks, "center" for centered overlays'
            ],
            
            // Repeat pattern spacing
            'watermark_repeat_h' => [
                'type' => 'text',
                'value' => $parsed['watermark_repeat_h'] ?? '',
                'label' => 'Repeat Horizontal Spacing',
                'desc' => 'Horizontal spacing between repeated watermarks (only used with repeat pattern)',
                'example' => '50% (half watermark width), 100px (100 pixels), leave empty for default'
            ],
            
            'watermark_repeat_v' => [
                'type' => 'text',
                'value' => $parsed['watermark_repeat_v'] ?? '',
                'label' => 'Repeat Vertical Spacing',
                'desc' => 'Vertical spacing between repeated watermarks (only used with repeat pattern)',
                'example' => '0 (no vertical spacing), 20px (20 pixel spacing)'
            ],
            
            // Position offset
            'watermark_offset_x' => [
                'type' => 'text',
                'value' => $parsed['watermark_offset_x'] ?? '0',
                'label' => 'Horizontal Offset',
                'desc' => 'Fine-tune watermark position with horizontal adjustment',
                'example' => '-20px (move left), 10% (move right), 0 (no adjustment)'
            ],
            
            'watermark_offset_y' => [
                'type' => 'text',
                'value' => $parsed['watermark_offset_y'] ?? '0',
                'label' => 'Vertical Offset',
                'desc' => 'Fine-tune watermark position with vertical adjustment',
                'example' => '10px (move down), -5% (move up), 0 (no adjustment)'
            ],
            
            // Rotation
            'watermark_rotation' => [
                'type' => 'text',
                'value' => $parsed['watermark_rotation'] ?? '0',
                'label' => 'Watermark Rotation',
                'desc' => 'Rotate the watermark image (anti-clockwise degrees)',
                'example' => '45 (45° rotation), -30 (clockwise), 0 (no rotation)'
            ]
        ];
    }

    // NOTE: Validation happens through getSubParameterDefinitions()
    // No custom validateParameter() override needed - uses parent implementation

    /**
     * Parse composite string into associative array
     * 
     * Supports two formats with priority:
     * 1. Named attributes: watermark_src:/path/logo.png|watermark_opacity:100|... (preferred)
     * 2. Legacy positional: /path/logo.png|0,0|100|center,center|0,0|0 (6-value format)
     * 
     * @param string $param_name Parameter name (should be 'watermark')
     * @param string $composite_string Composite parameter string
     * @return array Associative array of sub-parameters
     */
    public function parseCompositeString(string $param_name, string $composite_string): array
    {
        if (empty($composite_string)) {
            return $this->getDefaultValues();
        }

        // Priority 1: Named attributes format (has colons)
        if (strpos($composite_string, ':') !== false) {
            return $this->parseNamedAttributes($composite_string);
        }

        // Priority 2: Positional format (pipe-delimited)
        return $this->parsePositionalFormat($composite_string);
    }

    /**
     * Parse named attributes format
     * 
     * @param string $named_string Named attributes string
     * @return array Parsed values
     */
    private function parseNamedAttributes(string $named_string): array
    {
        $parts = explode('|', $named_string);
        $values = $this->getDefaultValues();

        foreach ($parts as $part) {
            if (strpos($part, ':') !== false) {
                list($key, $value) = explode(':', $part, 2);
                $key = trim($key);
                $value = trim($value);
                
                if (array_key_exists($key, $values)) {
                    $values[$key] = $value;
                }
            }
        }

        return $values;
    }

    /**
     * Parse positional format (legacy compatibility)
     * 
     * Legacy format: src|min_width,min_height|opacity|pos_h,pos_v|offset_x,offset_y|rotation
     * 
     * @param string $positional_string Positional format string
     * @return array Parsed values
     */
    private function parsePositionalFormat(string $positional_string): array
    {
        $parts = explode('|', $positional_string);
        $values = $this->getDefaultValues();

        // Part 1: watermark_src
        if (isset($parts[0]) && !empty(trim($parts[0]))) {
            $values['watermark_src'] = trim($parts[0]);
        }

        // Part 2: minimum_dimensions (min_width,min_height)
        if (isset($parts[1]) && !empty(trim($parts[1]))) {
            $dimensions = explode(',', $parts[1]);
            $values['watermark_min_width'] = trim($dimensions[0] ?? '0');
            $values['watermark_min_height'] = trim($dimensions[1] ?? '0');
        }

        // Part 3: opacity
        if (isset($parts[2]) && !empty(trim($parts[2]))) {
            $values['watermark_opacity'] = trim($parts[2]);
        }

        // Part 4: position (horizontal,vertical or repeat with spacing)
        if (isset($parts[3]) && !empty(trim($parts[3]))) {
            $position = explode(',', $parts[3]);
            $horizontalPart = trim($position[0] ?? 'center');
            
            // Check if it's a repeat pattern with spacing
            if (strpos($horizontalPart, 'repeat') === 0) {
                $values['watermark_position_h'] = 'repeat';
                
                // Extract repeat spacing if present
                if (count($position) >= 2) {
                    $values['watermark_repeat_h'] = trim($position[1] ?? '');
                    $values['watermark_repeat_v'] = trim($position[2] ?? '');
                }
            } else {
                $values['watermark_position_h'] = $horizontalPart;
                $values['watermark_position_v'] = trim($position[1] ?? 'center');
            }
        }

        // Part 5: offset (offset_x,offset_y)
        if (isset($parts[4]) && !empty(trim($parts[4]))) {
            $offset = explode(',', $parts[4]);
            $values['watermark_offset_x'] = trim($offset[0] ?? '0');
            $values['watermark_offset_y'] = trim($offset[1] ?? '0');
        }

        // Part 6: rotation
        if (isset($parts[5]) && !empty(trim($parts[5]))) {
            $values['watermark_rotation'] = trim($parts[5]);
        }

        return $values;
    }

    /**
     * Get default values for watermark sub-parameters
     * 
     * @return array Default values
     */
    private function getDefaultValues(): array
    {
        return [
            'watermark_src' => '',
            'watermark_min_width' => '0',
            'watermark_min_height' => '0',
            'watermark_opacity' => '100',
            'watermark_position_h' => 'center',
            'watermark_position_v' => 'center',
            'watermark_repeat_h' => '',
            'watermark_repeat_v' => '',
            'watermark_offset_x' => '0',
            'watermark_offset_y' => '0',
            'watermark_rotation' => '0'
        ];
    }

    /**
     * Process form data to generate watermark parameter value in named attributes format
     * 
     * Generates self-documenting named format: watermark_src:/path/logo.png|watermark_opacity:100|...
     * 
     * @param string $parameter_name Parameter name (should be 'watermark')
     * @param array $form_data Form submission data from control panel
     * @return string Formatted watermark parameter value in named attributes format
     */
    public function processParameterFromForm(string $parameter_name, array $form_data): string 
    {
        $named_parts = [];

        // Part 1: Watermark source (required)
        $watermark_src = trim($form_data['watermark_src'] ?? '');
        if (empty($watermark_src)) {
            return ''; // No watermark if source is empty
        }
        $named_parts[] = 'watermark_src:' . $watermark_src;

        // Part 2: Minimum dimensions
        $min_width = trim($form_data['watermark_min_width'] ?? '0');
        $min_height = trim($form_data['watermark_min_height'] ?? '0');
        $named_parts[] = 'watermark_min_width:' . $min_width;
        $named_parts[] = 'watermark_min_height:' . $min_height;

        // Part 3: Opacity
        $opacity = trim($form_data['watermark_opacity'] ?? '100');
        $named_parts[] = 'watermark_opacity:' . $opacity;

        // Part 4: Position (horizontal and vertical)
        $position_h = trim($form_data['watermark_position_h'] ?? 'center');
        $position_v = trim($form_data['watermark_position_v'] ?? 'center');
        $named_parts[] = 'watermark_position_h:' . $position_h;
        $named_parts[] = 'watermark_position_v:' . $position_v;

        // Part 5: Repeat spacing (if using repeat pattern)
        if ($position_h === 'repeat') {
            $repeat_h = trim($form_data['watermark_repeat_h'] ?? '');
            $repeat_v = trim($form_data['watermark_repeat_v'] ?? '');
            if (!empty($repeat_h)) {
                $named_parts[] = 'watermark_repeat_h:' . $repeat_h;
            }
            if (!empty($repeat_v)) {
                $named_parts[] = 'watermark_repeat_v:' . $repeat_v;
            }
        }

        // Part 6: Offset
        $offset_x = trim($form_data['watermark_offset_x'] ?? '0');
        $offset_y = trim($form_data['watermark_offset_y'] ?? '0');
        $named_parts[] = 'watermark_offset_x:' . $offset_x;
        $named_parts[] = 'watermark_offset_y:' . $offset_y;

        // Part 7: Rotation
        $rotation = trim($form_data['watermark_rotation'] ?? '0');
        $named_parts[] = 'watermark_rotation:' . $rotation;

        return implode('|', $named_parts);
    }

    /**
     * Validate watermark parameter value
     * 
     * Validates watermark parameter format, component values, and constraints.
     * Ensures source paths are provided, positions are valid, opacity is in range,
     * and rotation values are numeric.
     * 
     * @param string $param_name Parameter name being validated
     * @param mixed $value Parameter value to validate
     * @return bool|string True if valid, error message if invalid
     */
    public function validateParameter(string $param_name, $value): bool|string
    {
        if ($param_name !== 'watermark') {
            return parent::validateParameter($param_name, $value);
        }

        $parameter_value = (string) $value;

        // Empty watermark parameter is valid (no watermark)
        if (empty(trim($parameter_value))) {
            return true;
        }

        // Parse the composite string into sub-parameters
        $parsed = $this->parseCompositeString($param_name, $parameter_value);
        
        // Watermark source is required
        if (empty(trim($parsed['watermark_src'] ?? ''))) {
            return 'Watermark parameter requires a source image path';
        }

        // Validate minimum width
        $result = ParameterRegistry::validateValue('numeric', $parsed['watermark_min_width'] ?? '0', [
            'allow_negative' => false,
            'allow_percentage' => true,
            'allow_units' => ['px', '%'],
            'min_value' => 0,
            'default_unit' => 'px'
        ]);
        if (!$result->success) {
            return "Invalid minimum width: {$result->error}";
        }

        // Validate minimum height
        $result = ParameterRegistry::validateValue('numeric', $parsed['watermark_min_height'] ?? '0', [
            'allow_negative' => false,
            'allow_percentage' => true,
            'allow_units' => ['px', '%'],
            'min_value' => 0,
            'default_unit' => 'px'
        ]);
        if (!$result->success) {
            return "Invalid minimum height: {$result->error}";
        }

        // Validate opacity
        $result = ParameterRegistry::validateValue('percentage', $parsed['watermark_opacity'] ?? '100', [
            'min_value' => 0,
            'max_value' => 100,
            'format' => '0-100'
        ]);
        if (!$result->success) {
            return "Invalid opacity: {$result->error}";
        }

        // Validate horizontal position
        $result = ParameterRegistry::validateValue('enum', $parsed['watermark_position_h'] ?? 'center', [
            'allowed_values' => ['left', 'center', 'right', 'repeat'],
            'case_sensitive' => false
        ]);
        if (!$result->success) {
            return "Invalid horizontal position: {$result->error}";
        }

        // Validate vertical position
        $result = ParameterRegistry::validateValue('enum', $parsed['watermark_position_v'] ?? 'center', [
            'allowed_values' => ['top', 'center', 'bottom'],
            'case_sensitive' => false
        ]);
        if (!$result->success) {
            return "Invalid vertical position: {$result->error}";
        }

        // Validate offsets
        $result = ParameterRegistry::validateValue('numeric', $parsed['watermark_offset_x'] ?? '0', [
            'allow_negative' => true,
            'allow_percentage' => true,
            'allow_units' => ['px', '%'],
            'default_unit' => 'px'
        ]);
        if (!$result->success) {
            return "Invalid offset X: {$result->error}";
        }

        $result = ParameterRegistry::validateValue('numeric', $parsed['watermark_offset_y'] ?? '0', [
            'allow_negative' => true,
            'allow_percentage' => true,
            'allow_units' => ['px', '%'],
            'default_unit' => 'px'
        ]);
        if (!$result->success) {
            return "Invalid offset Y: {$result->error}";
        }

        // Validate rotation
        $result = ParameterRegistry::validateValue('numeric', $parsed['watermark_rotation'] ?? '0', [
            'allow_negative' => true,
            'allow_percentage' => false
        ]);
        if (!$result->success) {
            return "Invalid rotation: {$result->error}";
        }

        return true;
    }

    /**
     * Detect if parameter string uses named attribute format
     * 
     * Named format: "watermark_src:/path/logo.png|watermark_opacity:100|..."
     * Positional format: "/path/logo.png|0,0|100|center,center|0,0|0"
     * 
     * @param string $watermark_parameter Watermark parameter string
     * @return bool True if named attribute format detected
     */
    private function isNamedAttributeFormat(string $watermark_parameter): bool
    {
        // Named format has colon separators in pipe-delimited parts
        // Check first few parts for "name:value" pattern
        $parts = explode('|', trim($watermark_parameter));
        
        if (empty($parts)) {
            return false;
        }
        
        // Known attribute names (both full and alias forms)
        $known_names = [
            'watermark_src', 'src',
            'watermark_min_width', 'watermark_min_height', 'min_size', 'minimum_dimensions',
            'watermark_opacity', 'opacity',
            'watermark_position_h', 'watermark_position_v', 'position',
            'watermark_offset_x', 'watermark_offset_y', 'offset',
            'watermark_rotation', 'rotation'
        ];
        
        // Check first 3 parts for named format indicators
        $named_count = 0;
        $check_limit = min(3, count($parts));
        
        for ($i = 0; $i < $check_limit; $i++) {
            $part = trim($parts[$i]);
            if (strpos($part, ':') !== false) {
                list($name, ) = explode(':', $part, 2);
                if (in_array(trim($name), $known_names)) {
                    $named_count++;
                }
            }
        }
        
        // If 2 or more of first 3 parts match named format, assume named
        return $named_count >= 2;
    }

    /**
     * Convert named attribute format to positional pipe-delimited format
     * 
     * @param string $watermark_parameter Named attribute format string
     * @return string Positional pipe-delimited format string
     */
    private function convertNamedToPositionalFormat(string $watermark_parameter): string
    {
        // Parse named attributes into associative array
        $named_values = [];
        $parts = explode('|', trim($watermark_parameter));
        
        foreach ($parts as $part) {
            $part = trim($part);
            if (empty($part)) {
                continue;
            }
            
            // Split on first colon
            if (strpos($part, ':') !== false) {
                list($name, $value) = explode(':', $part, 2);
                $name = trim($name);
                $value = trim($value);
                
                // Map short aliases to full names
                $alias_map = [
                    'src' => 'watermark_src',
                    'min_size' => 'watermark_min_size',
                    'minimum_dimensions' => 'watermark_min_size',
                    'opacity' => 'watermark_opacity',
                    'position' => 'watermark_position',
                    'offset' => 'watermark_offset',
                    'rotation' => 'watermark_rotation'
                ];
                
                if (isset($alias_map[$name])) {
                    $name = $alias_map[$name];
                }
                
                $named_values[$name] = $value;
            }
        }
        
        // Handle compound values (position, offset, min_size)
        // Split position into horizontal and vertical
        if (isset($named_values['watermark_position']) && strpos($named_values['watermark_position'], ',') !== false) {
            list($h, $v) = explode(',', $named_values['watermark_position'], 2);
            $named_values['watermark_position_h'] = trim($h);
            $named_values['watermark_position_v'] = trim($v);
        }
        
        // Split offset into x and y
        if (isset($named_values['watermark_offset']) && strpos($named_values['watermark_offset'], ',') !== false) {
            list($x, $y) = explode(',', $named_values['watermark_offset'], 2);
            $named_values['watermark_offset_x'] = trim($x);
            $named_values['watermark_offset_y'] = trim($y);
        }
        
        // Split min_size into width and height
        if (isset($named_values['watermark_min_size']) && strpos($named_values['watermark_min_size'], ',') !== false) {
            list($w, $h) = explode(',', $named_values['watermark_min_size'], 2);
            $named_values['watermark_min_width'] = trim($w);
            $named_values['watermark_min_height'] = trim($h);
        }
        
        // Build positional format using defined order
        $positional = [];
        
        // 1. Watermark source (required)
        $positional[] = $named_values['watermark_src'] ?? '';
        
        // 2. Minimum dimensions (min_width,min_height)
        $min_width = $named_values['watermark_min_width'] ?? '0';
        $min_height = $named_values['watermark_min_height'] ?? '0';
        $positional[] = $min_width . ',' . $min_height;
        
        // 3. Opacity
        $positional[] = $named_values['watermark_opacity'] ?? '100';
        
        // 4. Position (horizontal,vertical)
        $position_h = $named_values['watermark_position_h'] ?? 'center';
        $position_v = $named_values['watermark_position_v'] ?? 'center';
        $positional[] = $position_h . ',' . $position_v;
        
        // 5. Offset (horizontal,vertical)
        $offset_x = $named_values['watermark_offset_x'] ?? '0';
        $offset_y = $named_values['watermark_offset_y'] ?? '0';
        $positional[] = $offset_x . ',' . $offset_y;
        
        // 6. Rotation
        $positional[] = $named_values['watermark_rotation'] ?? '0';
        
        // Join with pipe and trim trailing empty values
        return rtrim(implode('|', $positional), '|');
    }
}
