"""
Post-Extraction Logger Plugin

Appends extracted results and final trial status to the log.
"""

from typing import Dict, Any, Optional
from pathlib import Path
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


def log_extracted_results(context: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Log extracted results to the trial log file.

    Args:
        context: Hook context containing:
            - trial_number: Current trial number
            - design_variables: Dict of variable values
            - extracted_results: Dict of all extracted objectives and constraints
            - result_path: Path to result file
            - working_dir: Current working directory
    """
    trial_num = context.get('trial_number', '?')
    extracted_results = context.get('extracted_results', {})
    result_path = context.get('result_path', '')

    # Get the output directory from context (passed by runner)
    output_dir = Path(context.get('output_dir', 'optimization_results'))
    log_dir = output_dir / 'trial_logs'
    if not log_dir.exists():
        logger.warning(f"Log directory not found: {log_dir}")
        return None

    # Find trial log file
    log_files = list(log_dir.glob(f'trial_{trial_num:03d}_*.log'))
    if not log_files:
        logger.warning(f"No log file found for trial {trial_num}")
        return None

    # Use most recent log file
    log_file = sorted(log_files)[-1]

    with open(log_file, 'a') as f:
        f.write(f"[{datetime.now().strftime('%H:%M:%S')}] POST_EXTRACTION: Results extracted\n")
        f.write("\n")

        f.write("-" * 80 + "\n")
        f.write("EXTRACTED RESULTS\n")
        f.write("-" * 80 + "\n")

        for result_name, result_value in extracted_results.items():
            f.write(f"  {result_name:30s} = {result_value:12.4f}\n")

        f.write("\n")
        f.write(f"[{datetime.now().strftime('%H:%M:%S')}] Evaluating constraints...\n")
        f.write(f"[{datetime.now().strftime('%H:%M:%S')}] Calculating total objective...\n")
        f.write("\n")

    return {'logged': True}


def register_hooks(hook_manager):
    """Register this plugin's hooks with the manager."""
    hook_manager.register_hook(
        hook_point='post_extraction',
        function=log_extracted_results,
        description='Log extracted results to trial log',
        name='log_extracted_results',
        priority=10
    )
