"""CSV export functionality."""

import csv
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
from sqlalchemy.orm import Session
from src.core.database import get_database, Trade, Order
from src.core.logger import get_logger

logger = get_logger(__name__)


class CSVExporter:
    """CSV export functionality."""
    
    def __init__(self):
        """Initialize CSV exporter."""
        self.db = get_database()
        self.logger = get_logger(__name__)
    
    def export_trades(
        self,
        filepath: Path,
        paper_trading: bool = True,
        start_date: Optional[datetime] = None,
        end_date: Optional[datetime] = None
    ) -> bool:
        """Export trades to CSV.
        
        Args:
            filepath: Output file path
            paper_trading: Filter by paper trading
            start_date: Start date filter
            end_date: End date filter
            
        Returns:
            True if export successful
        """
        session = self.db.get_session()
        try:
            query = session.query(Trade).filter_by(paper_trading=paper_trading)
            if start_date:
                query = query.filter(Trade.timestamp >= start_date)
            if end_date:
                query = query.filter(Trade.timestamp <= end_date)
            
            trades = query.order_by(Trade.timestamp).all()
            
            with open(filepath, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow([
                    'Timestamp', 'Symbol', 'Side', 'Quantity', 'Price', 'Fee', 'Total'
                ])
                
                for trade in trades:
                    writer.writerow([
                        trade.timestamp.isoformat(),
                        trade.symbol,
                        trade.side.value,
                        float(trade.quantity),
                        float(trade.price),
                        float(trade.fee),
                        float(trade.total),
                    ])
            
            logger.info(f"Exported {len(trades)} trades to {filepath}")
            return True
        except Exception as e:
            logger.error(f"Failed to export trades: {e}")
            return False
        finally:
            session.close()
    
    def export_portfolio(self, filepath: Path) -> bool:
        """Export portfolio snapshot to CSV.
        
        Args:
            filepath: Output file path
            
        Returns:
            True if export successful
        """
        from src.portfolio.tracker import get_portfolio_tracker
        
        tracker = get_portfolio_tracker()
        portfolio = tracker.get_current_portfolio()
        
        try:
            with open(filepath, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['Symbol', 'Quantity', 'Entry Price', 'Current Price', 'Unrealized P&L'])
                
                for pos in portfolio['positions']:
                    writer.writerow([
                        pos['symbol'],
                        pos['quantity'],
                        pos['entry_price'],
                        pos['current_price'],
                        pos['unrealized_pnl'],
                    ])
            
            logger.info(f"Exported portfolio to {filepath}")
            return True
        except Exception as e:
            logger.error(f"Failed to export portfolio: {e}")
            return False


# Global CSV exporter
_csv_exporter: Optional[CSVExporter] = None


def get_csv_exporter() -> CSVExporter:
    """Get global CSV exporter instance."""
    global _csv_exporter
    if _csv_exporter is None:
        _csv_exporter = CSVExporter()
    return _csv_exporter

