# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
钩子装饰器 - 提供便捷的装饰器语法
"""

import functools
from typing import Callable, Optional, Any
from .registry import registry
from .signal import Priority

logger = None  # 延迟导入避免循环


def hook(
    hook_name: str,
    *,
    sender: Optional[str] = None,
    priority: Priority = Priority.NORMAL,
    condition: Optional[Callable] = None,
    once: bool = False
):
    """
    钩子装饰器 - 注册函数为钩子处理器
    
    用法:
        @hook('page.User.on_update', sender='User', priority=Priority.HIGH)
        def handle_user_update(page, **kwargs):
            print(f"User {page.name} updated")
        
        @hook('scheduler.daily', condition=lambda: datetime.now().hour == 0)
        def daily_task(**kwargs):
            # 只在午夜执行
            pass
    """
    def decorator(func: Callable) -> Callable:
        registry.connect(
            hook_name,
            func,
            sender=sender,
            priority=priority,
            condition=condition,
            once=once
        )
        return func
    
    return decorator


def register_hook(
    hook_name: str,
    handler: Optional[Callable] = None,
    *,
    sender: Optional[str] = None,
    priority: Priority = Priority.NORMAL,
    condition: Optional[Callable] = None,
    once: bool = False
):
    """
    注册钩子（可用作装饰器或函数调用）
    
    用法:
        # 装饰器方式
        @register_hook('page.User.on_update', sender='User')
        def handler(page, **kwargs):
            pass
        
        # 函数调用方式
        register_hook('page.User.on_update', my_handler, sender='User')
    """
    if handler is None:
        # 用作装饰器
        return hook(
            hook_name,
            sender=sender,
            priority=priority,
            condition=condition,
            once=once
        )
    
    # 直接注册
    registry.connect(
        hook_name,
        handler,
        sender=sender,
        priority=priority,
        condition=condition,
        once=once
    )
    return handler

