"""
Auto-generated tool handlers.
Managed by AI Tool Builder. Each handler below was generated by the LLM
and reviewed by the user before activation.
"""

import json
import os
import re
import requests
from tool_handlers import register_handler


def load_generated_handlers():
    """Load all generated handlers by executing handler blocks in this file."""
    here = os.path.dirname(os.path.abspath(__file__))
    gen_file = os.path.join(here, 'generated_handlers.py')
    if not os.path.isfile(gen_file):
        return 0

    with open(gen_file, 'r', encoding='utf-8') as f:
        content = f.read()

    blocks = re.findall(
        r'(^# --- Generated:.*?(?=\n# --- Generated:|\Z))',
        content, re.DOTALL | re.MULTILINE
    )

    count = 0
    for block in blocks:
        block = block.strip()
        if not block or '@register_handler' not in block:
            continue
        block_label = block.split('\n', 1)[0][:80]
        try:
            exec(compile(block, f'<gen:{block_label}>', 'exec'), {
                '__builtins__': {
                    'True': True, 'False': False, 'None': None,
                    'int': int, 'float': float, 'str': str, 'bool': bool,
                    'list': list, 'dict': dict, 'tuple': tuple, 'set': set,
                    'len': len, 'range': range, 'enumerate': enumerate,
                    'isinstance': isinstance, 'print': print,
                    'min': min, 'max': max, 'abs': abs, 'round': round,
                    'sorted': sorted, 'reversed': reversed,
                    'zip': zip, 'map': map, 'filter': filter,
                    'ValueError': ValueError, 'TypeError': TypeError,
                    'KeyError': KeyError, 'Exception': Exception,
                },
                'register_handler': register_handler,
                'requests': requests,
                'json': json,
                're': re,
            })
            count += 1
        except Exception as e:
            print(f'[GenHandlers] Error loading block ({block_label}): {e}')

    return count


# Generated handlers below
# ============================================================
