"""Multi-timeframe strategy framework with synchronization."""

from typing import Dict, List, Optional, Any
from datetime import datetime
from decimal import Decimal
from src.core.logger import get_logger

logger = get_logger(__name__)


class TimeframeManager:
    """Manages multiple timeframes for strategies."""
    
    def __init__(self, timeframes: List[str]):
        """Initialize timeframe manager.
        
        Args:
            timeframes: List of timeframes (e.g., ['1h', '15m'])
        """
        self.timeframes = sorted(timeframes, key=self._timeframe_to_seconds, reverse=True)
        self.data: Dict[str, Dict[str, Any]] = {tf: {} for tf in self.timeframes}
        self.last_update: Dict[str, datetime] = {tf: datetime.min for tf in self.timeframes}
    
    def _timeframe_to_seconds(self, tf: str) -> int:
        """Convert timeframe to seconds for sorting.
        
        Args:
            tf: Timeframe string (e.g., '1h', '15m')
            
        Returns:
            Seconds
        """
        if tf.endswith('m'):
            return int(tf[:-1]) * 60
        elif tf.endswith('h'):
            return int(tf[:-1]) * 3600
        elif tf.endswith('d'):
            return int(tf[:-1]) * 86400
        return 0
    
    def update(self, timeframe: str, symbol: str, data: Dict[str, Any]):
        """Update data for a timeframe.
        
        Args:
            timeframe: Timeframe
            symbol: Trading symbol
            data: Market data
        """
        if timeframe not in self.timeframes:
            logger.warning(f"Unknown timeframe: {timeframe}")
            return
        
        if symbol not in self.data[timeframe]:
            self.data[timeframe][symbol] = {}
        
        self.data[timeframe][symbol].update(data)
        self.last_update[timeframe] = datetime.utcnow()
    
    def get_data(self, timeframe: str, symbol: str) -> Optional[Dict[str, Any]]:
        """Get data for a timeframe.
        
        Args:
            timeframe: Timeframe
            symbol: Trading symbol
            
        Returns:
            Data dictionary or None
        """
        return self.data.get(timeframe, {}).get(symbol)
    
    def get_all_timeframes(self, symbol: str) -> Dict[str, Dict[str, Any]]:
        """Get data for all timeframes.
        
        Args:
            symbol: Trading symbol
            
        Returns:
            Dictionary of timeframe -> data
        """
        return {
            tf: self.data[tf].get(symbol, {})
            for tf in self.timeframes
        }
    
    def is_synchronized(self, symbol: str, max_age_seconds: int = 300) -> bool:
        """Check if all timeframes are synchronized (recently updated).
        
        Args:
            symbol: Trading symbol
            max_age_seconds: Maximum age in seconds
            
        Returns:
            True if all timeframes are synchronized
        """
        now = datetime.utcnow()
        for tf in self.timeframes:
            if symbol not in self.data[tf]:
                return False
            age = (now - self.last_update[tf]).total_seconds()
            if age > max_age_seconds:
                return False
        return True

