"""PDF report generation."""

from pathlib import Path
from datetime import datetime
from typing import Dict, Any, Optional
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from src.core.logger import get_logger

logger = get_logger(__name__)


class PDFGenerator:
    """PDF report generation."""
    
    def __init__(self):
        """Initialize PDF generator."""
        self.logger = get_logger(__name__)
    
    def generate_performance_report(
        self,
        filepath: Path,
        metrics: Dict[str, Any],
        title: str = "Portfolio Performance Report"
    ) -> bool:
        """Generate performance report PDF.
        
        Args:
            filepath: Output file path
            metrics: Performance metrics dictionary
            title: Report title
            
        Returns:
            True if generation successful
        """
        try:
            doc = SimpleDocTemplate(str(filepath), pagesize=letter)
            story = []
            styles = getSampleStyleSheet()
            
            # Title
            story.append(Paragraph(title, styles['Title']))
            story.append(Spacer(1, 12))
            
            # Metrics table
            data = [
                ['Metric', 'Value'],
                ['Total Return', f"{metrics.get('total_return_percent', 0):.2f}%"],
                ['Sharpe Ratio', f"{metrics.get('sharpe_ratio', 0):.2f}"],
                ['Sortino Ratio', f"{metrics.get('sortino_ratio', 0):.2f}"],
                ['Max Drawdown', f"{metrics.get('max_drawdown', 0):.2%}"],
                ['Win Rate', f"{metrics.get('win_rate', 0):.2%}"],
            ]
            
            table = Table(data)
            table.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('FONTSIZE', (0, 0), (-1, 0), 14),
                ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ]))
            
            story.append(table)
            story.append(Spacer(1, 12))
            story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal']))
            
            doc.build(story)
            logger.info(f"Generated PDF report: {filepath}")
            return True
        except Exception as e:
            logger.error(f"Failed to generate PDF report: {e}")
            return False
    
    def generate_backtest_report(
        self,
        results: Dict[str, Any],
        filepath: str
    ) -> bool:
        """Generate backtest report PDF.
        
        Args:
            results: Backtest results dictionary
            filepath: Output file path
            
        Returns:
            True if generation successful
        """
        return self.generate_performance_report(
            Path(filepath),
            results,
            "Backtest Report"
        )


# Global PDF generator
_pdf_generator: Optional[PDFGenerator] = None


def get_pdf_generator() -> PDFGenerator:
    """Get global PDF generator instance."""
    global _pdf_generator
    if _pdf_generator is None:
        _pdf_generator = PDFGenerator()
    return _pdf_generator

