# Flyto2 Core - Source Available License
# Copyright (c) 2025 Flyto2. All Rights Reserved.
#
# This source code is licensed under the Flyto2 Source Available License v1.0.
# Commercial use requires a license. See LICENSE for details.

"""
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.filter',
    version='1.0.0',
    category='atomic',
    subcategory='array',
    tags=['array', 'filter', 'data', 'atomic'],
    label='Filter Array',
    label_key='modules.array.filter.label',
    description='Filter array elements by condition',
    description_key='modules.array.filter.description',
    icon='ListFilter',
    color='#10B981',

    # Connection types
    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.FILTER_CONDITION(required=True),
        presets.COMPARE_VALUE(required=True),
    ),
    output_schema={
        'filtered': {
            'type': 'array',
            'description': 'Filtered array'
        ,
                'description_key': 'modules.array.filter.output.filtered.description'},
        'count': {
            'type': 'number',
            'description': 'Number of items in filtered array'
        ,
                'description_key': 'modules.array.filter.output.count.description'}
    },
    examples=[
        {
            'title': 'Filter numbers greater than 5',
            'title_key': 'modules.array.filter.examples.numbers.title',
            'params': {
                'array': [1, 5, 10, 15, 3],
                'condition': 'gt',
                'value': '5'
            }
        }
    ],
    author='Flyto Team',
    license='MIT',
    timeout_ms=5000,
)
async def array_filter(context):
    """Filter array by condition"""
    params = context['params']
    array = params['array']
    condition = params['condition']
    value = params['value']

    # Try to convert value to number if possible
    try:
        value = float(value)
    except (ValueError, TypeError):
        pass

    filtered = []
    for item in array:
        if condition == 'gt':
            if isinstance(item, (int, float)) and isinstance(value, (int, float)) and item > value:
                filtered.append(item)
        elif condition == 'lt':
            if isinstance(item, (int, float)) and isinstance(value, (int, float)) and item < value:
                filtered.append(item)
        elif condition == 'eq':
            if item == value:
                filtered.append(item)
        elif condition == 'ne':
            if item != value:
                filtered.append(item)
        elif condition == 'contains':
            if isinstance(item, str) and isinstance(value, str) and value in item:
                filtered.append(item)

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


