"""Data persistence."""

from decimal import Decimal
from datetime import datetime
from typing import List, Optional
from sqlalchemy.orm import Session
from src.core.database import get_database, MarketData
from src.core.logger import get_logger

logger = get_logger(__name__)


class DataStorage:
    """Manages data storage and persistence."""
    
    def __init__(self):
        """Initialize data storage."""
        self.db = get_database()
        self.logger = get_logger(__name__)
    
    def store_ohlcv(
        self,
        exchange: str,
        symbol: str,
        timeframe: str,
        timestamp: datetime,
        open: Decimal,
        high: Decimal,
        low: Decimal,
        close: Decimal,
        volume: Decimal
    ):
        """Store OHLCV data.
        
        Args:
            exchange: Exchange name
            symbol: Trading symbol
            timeframe: Timeframe
            timestamp: Timestamp
            open: Open price
            high: High price
            low: Low price
            close: Close price
            volume: Volume
        """
        session = self.db.get_session()
        try:
            # Check if exists
            existing = session.query(MarketData).filter_by(
                exchange=exchange,
                symbol=symbol,
                timeframe=timeframe,
                timestamp=timestamp
            ).first()
            
            if not existing:
                market_data = MarketData(
                    exchange=exchange,
                    symbol=symbol,
                    timeframe=timeframe,
                    timestamp=timestamp,
                    open=open,
                    high=high,
                    low=low,
                    close=close,
                    volume=volume
                )
                session.add(market_data)
                session.commit()
        except Exception as e:
            session.rollback()
            logger.error(f"Failed to store OHLCV data: {e}")
        finally:
            session.close()

