"""
Array Operation Modules
Array data manipulation and transformation
"""

from typing import Any, Dict
from ...base import BaseModule
from ...registry import register_module
from ...schema import compose, presets
from ...errors import ValidationError, InvalidTypeError


@register_module(
    module_id='array.sort',
    version='1.0.0',
    category='atomic',
    subcategory='array',
    tags=['array', 'sort', 'data', 'atomic'],
    label='Sort Array',
    label_key='modules.array.sort.label',
    description='Sort array elements in ascending or descending order',
    description_key='modules.array.sort.description',
    icon='ArrowUpDown',
    color='#10B981',


    # Type definitions for connection validation
    input_types=['array'],
    output_types=['array'],

    can_receive_from=['*'],
    can_connect_to=['*'],    # Phase 2: Execution settings
    # No timeout - instant array operation
    retryable=False,  # Logic errors won't fix themselves
    concurrent_safe=True,  # Stateless operation

    # Phase 2: Security settings
    requires_credentials=False,
    handles_sensitive_data=False,
    required_permissions=[],

    # Schema-driven params
    params_schema=compose(
        presets.INPUT_ARRAY(required=True),
        presets.SORT_ORDER(default='asc'),
    ),
    output_schema={
        'sorted': {
            'type': 'array',
            'description': 'Sorted array'
        ,
                'description_key': 'modules.array.sort.output.sorted.description'},
        'count': {
            'type': 'number',
            'description': 'Number of items'
        ,
                'description_key': 'modules.array.sort.output.count.description'}
    },
    examples=[
        {
            'title': 'Sort numbers ascending',
            'title_key': 'modules.array.sort.examples.ascending.title',
            'params': {
                'array': [5, 2, 8, 1, 9],
                'order': 'asc'
            }
        }
    ],
    author='Flyto Team',
    license='MIT',
    timeout_ms=5000,
)
async def array_sort(context):
    """Sort array elements"""
    params = context['params']
    array = params['array']
    order = params.get('order', 'asc')

    sorted_array = sorted(array, reverse=(order == 'desc'))

    return {
        'ok': True,
        'data': {
            'sorted': sorted_array,
            'count': len(sorted_array)
        }
    }


