"""
Performance monitoring context manager for DataManager operations.
"""

import time
from typing import Optional
from contextlib import contextmanager

from .monitoring import PerformanceMonitor


class PerformanceContext:
    """Context manager for performance monitoring during data operations"""

    def __init__(self, monitor: PerformanceMonitor, operation_name: str):
        self.monitor = monitor
        self.operation_name = operation_name
        self.start_time: Optional[float] = None
        self.end_time: Optional[float] = None

    def __enter__(self):
        """Start performance monitoring"""
        self.start_time = time.time()
        self.monitor.start_monitoring(self.operation_name)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Stop performance monitoring"""
        self.end_time = time.time()
        self.monitor.stop_monitoring()

    @property
    def elapsed_time(self) -> float:
        """Get elapsed time for this operation"""
        if self.start_time is None:
            return 0.0
        end = self.end_time or time.time()
        return end - self.start_time

    @property
    def peak_memory_gb(self) -> float:
        """Get peak memory usage during this operation"""
        return self.monitor.get_peak_memory()
