"""
Example hook implementations for django-cronjob-utils.

This file demonstrates how to use the hook system to add custom logic
before and after cronjob execution.

The hooks system allows you to:
- Check if a previous cronjob has completed successfully before running the current one
- Enforce business rules (e.g., daily limits, permissions)
- Log execution attempts
- Send custom notifications
- Validate execution conditions

Usage:
    1. Copy the hooks you need to your project
    2. Modify them according to your requirements
    3. Register them in your Django app's AppConfig.ready() method
"""

import logging
from datetime import date

from django_package_hooks import HookType, register_hook, HookRejectionError
from django_cronjob_utils.hooks import CronjobHookContext
from django_cronjob_utils.models import CronExecution

logger = logging.getLogger(__name__)


# =============================================================================
# PRE HOOKS - Execute before cronjob (can reject execution)
# =============================================================================


def check_dependency_completed(context: CronjobHookContext) -> bool:
    """
    PRE hook: Check if a dependent cronjob has completed successfully.
    
    This is useful when you have cronjobs that depend on other cronjobs.
    For example, a commission calculation job that depends on a data sync job.
    
    Priority: 10 (dependency checks should run early)
    
    To use this hook, set the 'dependency_task_code' in the task options.
    """
    # Get dependency task code from metadata or options
    dependency_task_code = context.metadata.get('dependency_task_code') or context.options.get('dependency_task_code')
    
    if not dependency_task_code:
        # No dependency specified, allow execution
        return True
    
    # Check if dependency task completed successfully for this execution date
    dependency_completed = CronExecution.objects.filter(
        task_code=dependency_task_code,
        execution_date=context.execution_date,
        success=True,
        completed=True
    ).exists()
    
    if not dependency_completed:
        raise HookRejectionError(
            error_code='DEPENDENCY_NOT_COMPLETED',
            message=f'Dependency task {dependency_task_code} has not completed successfully for {context.execution_date}',
            details={
                'dependency_task_code': dependency_task_code,
                'execution_date': str(context.execution_date),
                'current_task_code': context.task_code
            }
        )
    
    logger.info(
        f"Task {context.task_code}: Dependency {dependency_task_code} "
        f"completed successfully for {context.execution_date}"
    )
    return True


def log_execution_attempt(context: CronjobHookContext) -> None:
    """
    POST hook: Log execution attempts for audit trail.
    
    Priority: 100 (logging should happen early in POST hooks)
    """
    execution = None
    if context.execution_id:
        try:
            execution = CronExecution.objects.get(pk=context.execution_id)
        except CronExecution.DoesNotExist:
            pass
    
    if execution:
        logger.info(
            f"Task {context.task_name} ({context.task_code}) executed: "
            f"date={context.execution_date}, success={execution.success}, "
            f"duration={execution.duration}s, message={execution.message}"
        )
    else:
        logger.info(
            f"Task {context.task_name} ({context.task_code}) execution attempted "
            f"for date={context.execution_date}"
        )


def register_example_cronjob_hooks():
    """
    Register all example hooks.
    
    Call this function in your Django app's AppConfig.ready() method:
    
        class MyAppConfig(AppConfig):
            name = 'myapp'
            
            def ready(self):
                from myapp.cronjob_hooks import register_example_cronjob_hooks
                register_example_cronjob_hooks()
    """
    # PRE hooks (validation/dependency checks)
    register_hook(
        name='check_dependency_completed',
        hook_type=HookType.PRE,
        callback=check_dependency_completed,
        operation='execute',
        priority=10
    )
    
    # POST hooks (logging/notifications/metrics)
    register_hook(
        name='log_execution_attempt',
        hook_type=HookType.POST,
        callback=log_execution_attempt,
        operation='execute',
        priority=100
    )
