"""
Calculate safety factor
Auto-generated lifecycle hook by Atomizer Phase 2.9

Hook Point: post_calculation
Inputs: max_stress, yield_strength
Outputs: safety_factor
"""

import logging
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)


def safety_factor_hook(context: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Calculate safety factor

    Args:
        context: Hook context containing:
            - trial_number: Current optimization trial
            - results: Dictionary with extracted FEA results
            - calculations: Dictionary with inline calculation results

    Returns:
        Dictionary with calculated values to add to context
    """
    logger.info(f"Executing safety_factor_hook for trial {context.get('trial_number', 'unknown')}")

    # Extract inputs from context
    results = context.get('results', {})
    calculations = context.get('calculations', {})

    max_stress = calculations.get('max_stress') or results.get('max_stress')
    if max_stress is None:
        logger.error(f"Required input 'max_stress' not found in context")
        raise ValueError(f"Missing required input: max_stress")

    yield_strength = calculations.get('yield_strength') or results.get('yield_strength')
    if yield_strength is None:
        logger.error(f"Required input 'yield_strength' not found in context")
        raise ValueError(f"Missing required input: yield_strength")

    # Calculate using custom formula
    safety_factor = yield_strength / max_stress

    logger.info(f"safety_factor = {safety_factor:.6f}")

    return {
        'safety_factor': safety_factor
    }


def register_hooks(hook_manager):
    """
    Register this hook with the HookManager.

    This function is called automatically when the plugin is loaded.

    Args:
        hook_manager: The HookManager instance
    """
    hook_manager.register_hook(
        hook_point='post_calculation',
        function=safety_factor_hook,
        description="Calculate safety factor",
        name="safety_factor_hook",
        priority=100,
        enabled=True
    )
    logger.info(f"Registered safety_factor_hook at post_calculation")
