"""
Report generation module (HTML + PDF)
"""
import os
import logging
from datetime import datetime
from pathlib import Path
from typing import Dict, List
from weasyprint import HTML, CSS
from weasyprint.text.fonts import FontConfiguration

from .config import settings

logger = logging.getLogger(__name__)


class ReportGenerator:
    """Generator for HTML and PDF reports."""

    def __init__(self):
        """Initialize report generator."""
        self.reports_dir = Path(settings.reports_dir)
        self.reports_dir.mkdir(parents=True, exist_ok=True)

    def generate_html_content(
        self,
        sentiments: Dict,
        total_items: int,
        negative_items: List[Dict]
    ) -> str:
        """
        Generate HTML report content.

        Args:
            sentiments: Dictionary with neg/pos/neu counts
            total_items: Total number of items analyzed
            negative_items: List of negative items

        Returns:
            HTML content as string
        """
        percent_neg = (sentiments['neg'] / total_items * 100) if total_items > 0 else 0
        percent_pos = (sentiments['pos'] / total_items * 100) if total_items > 0 else 0
        percent_neu = (sentiments['neu'] / total_items * 100) if total_items > 0 else 0

        # Crisis alert
        crisis_level = "CRÍTICO" if percent_neg > 60 else "MODERADO" if percent_neg > 40 else "BAIXO"
        crisis_color = "#d32f2f" if percent_neg > 60 else "#f57c00" if percent_neg > 40 else "#388e3c"

        html = f"""<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relatório de Crise: {settings.search_query}</title>
    <style>
        @page {{
            margin: 2cm;
            @top-right {{
                content: "Página " counter(page);
                font-family: Arial, sans-serif;
                font-size: 10pt;
                color: #666;
            }}
        }}
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #ffffff;
            color: #222;
            line-height: 1.6;
            padding: 20px;
        }}
        .container {{
            max-width: 1000px;
            margin: auto;
            background: #fff;
        }}
        h1 {{
            text-align: center;
            color: #d32f2f;
            font-size: 2em;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-bottom: 3px solid #d32f2f;
            padding-bottom: 10px;
        }}
        .subtitle {{
            text-align: center;
            font-size: 0.95em;
            color: #666;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }}
        .stats {{
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin: 30px 0;
        }}
        .stat {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }}
        .stat h3 {{
            margin: 0;
            font-size: 2.5em;
            font-weight: bold;
        }}
        .stat p {{
            margin: 8px 0 0;
            font-size: 0.9em;
        }}
        .stat .percent {{
            font-size: 0.8em;
            margin-top: 5px;
        }}
        .stat.neg {{ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }}
        .stat.pos {{ background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }}
        .stat.neu {{ background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }}

        .alert {{
            background: #ffebee;
            border-left: 5px solid {crisis_color};
            padding: 20px;
            margin: 30px 0;
            font-weight: bold;
            color: {crisis_color};
            border-radius: 8px;
        }}
        .alert .number {{
            font-size: 2em;
            display: inline-block;
            margin-right: 10px;
        }}

        .action {{
            background: #e8f5e9;
            border-left: 5px solid #388e3c;
            padding: 25px;
            margin: 30px 0;
            border-radius: 8px;
        }}
        .action h2 {{
            margin: 0 0 15px;
            color: #1b5e20;
            font-size: 1.3em;
        }}
        .action ul {{
            margin: 0;
            padding-left: 25px;
        }}
        .action li {{
            margin: 12px 0;
            line-height: 1.6;
        }}
        .action strong {{ color: #2e7d32; }}

        h2.section-title {{
            color: #d32f2f;
            border-bottom: 3px solid #d32f2f;
            padding-bottom: 10px;
            margin: 40px 0 20px;
            font-size: 1.5em;
        }}

        .item {{
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
            background: #fafafa;
            page-break-inside: avoid;
        }}
        .item .title {{
            font-weight: 600;
            margin-bottom: 8px;
            color: #333;
            font-size: 1.05em;
        }}
        .item .meta {{
            font-size: 0.85em;
            color: #666;
            margin-bottom: 8px;
        }}
        .item .source {{
            color: #d32f2f;
            font-weight: 500;
        }}
        .item .reason {{
            font-size: 0.9em;
            color: #555;
            font-style: italic;
            margin-top: 8px;
            padding-left: 10px;
            border-left: 2px solid #ddd;
        }}
        .item .sent {{
            display: inline-block;
            font-weight: bold;
            font-size: 0.75em;
            padding: 4px 10px;
            border-radius: 20px;
            color: #fff;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }}
        .sent.neg {{ background: #f5576c; }}
        .badge-reclameaqui {{
            background: #ff4444;
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: bold;
            margin-left: 8px;
        }}

        footer {{
            text-align: center;
            margin-top: 50px;
            padding-top: 20px;
            border-top: 2px solid #eee;
            font-size: 0.85em;
            color: #777;
        }}

        @media print {{
            body {{ background: white; }}
            .stat {{ page-break-inside: avoid; }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>📊 RELATÓRIO DE CRISE: {settings.search_query}</h1>
        <p class="subtitle">
            <strong>Período:</strong> Últimos {settings.num_emails} emails de Google Alerts<br>
            <strong>Total de alertas:</strong> {total_items} notícias analisadas<br>
            <strong>Gerado em:</strong> {datetime.now().strftime('%d/%m/%Y às %H:%M:%S')}<br>
            <strong>Nível de Crise:</strong> <span style="color:{crisis_color}; font-weight:bold;">{crisis_level}</span>
        </p>

        <div class="stats">
            <div class="stat neg">
                <h3>{sentiments['neg']}</h3>
                <p>Negativos</p>
                <div class="percent">{percent_neg:.1f}%</div>
            </div>
            <div class="stat pos">
                <h3>{sentiments['pos']}</h3>
                <p>Positivos</p>
                <div class="percent">{percent_pos:.1f}%</div>
            </div>
            <div class="stat neu">
                <h3>{sentiments['neu']}</h3>
                <p>Neutros</p>
                <div class="percent">{percent_neu:.1f}%</div>
            </div>
        </div>

        <div class="alert">
            <span class="number">{percent_neg:.0f}%</span>
            DOS ALERTAS SÃO NEGATIVOS → Nível de crise: {crisis_level}. {'Ação imediata necessária!' if percent_neg > 60 else 'Monitoramento recomendado.'}
        </div>

        <div class="action">
            <h2>🎯 PLANO DE AÇÃO URGENTE</h2>
            <ul>
                <li><strong>1. Resolver Reclame Aqui (hoje):</strong> Acesse o painel administrativo → responda todas as reclamações pendentes → solicite desativação de posts resolvidos.</li>
                <li><strong>2. Desindexar do Google (24h):</strong> Google Search Console → "Remover URL" → envie links das páginas negativas (especialmente Reclame Aqui).</li>
                <li><strong>3. Monitoramento diário:</strong> Configure novo alerta: <code>"{settings.search_query}" -site:reclameaqui.com.br</code></li>
                <li><strong>4. Contramedidas de PR:</strong> Publique nota oficial + invista R$ 50k em assessoria de imprensa positiva (prazo: 3 dias).</li>
                <li><strong>5. SEO Defensivo:</strong> Crie 5 artigos positivos em sites de autoridade para empurrar resultados negativos para 2ª página.</li>
            </ul>
        </div>

        <h2 class="section-title">⚠️ TOP 10 ALERTAS NEGATIVOS</h2>
"""

        if not negative_items:
            html += '<p style="text-align:center; color:#999; padding:20px;">Nenhum alerta negativo identificado.</p>'

        for idx, item in enumerate(negative_items[:10], 1):
            date_display = item['date'].split(',')[0] if ',' in item['date'] else item['date'][:20]
            reclameaqui_badge = '<span class="badge-reclameaqui">RECLAME AQUI</span>' if item.get('is_reclameaqui') else ''

            html += f"""
        <div class="item">
            <div style="display:flex; justify-content:space-between; align-items:start; margin-bottom:8px;">
                <div style="flex:1;">
                    <div class="title">#{idx} - {item['title'][:150]}{'...' if len(item['title']) > 150 else ''}{reclameaqui_badge}</div>
                </div>
                <span class="sent neg">NEGATIVO</span>
            </div>
            <div class="meta">
                📅 {date_display} |
                🌐 <span class="source">{item['source']}</span>
            </div>
            <div class="meta" style="word-break: break-all;">
                🔗 {item['link'][:100]}{'...' if len(item['link']) > 100 else ''}
            </div>
            {f'<div class="reason">💡 {item.get("reason", "")}</div>' if item.get("reason") else ''}
        </div>
"""

        html += f"""
        <footer>
            <div><strong>Relatório gerado automaticamente por Google Alerts Reporter v{settings.app_version}</strong></div>
            <div style="margin-top:10px; font-size:0.8em;">
                Powered by Gmail API + {'Grok 4 (xAI API)' if not settings.xai_api_key == 'SEU_API_KEY_AQUI' else 'Análise Mock'} |
                Próxima atualização: {settings.auto_refresh_interval // 3600}h
            </div>
        </footer>
    </div>
</body>
</html>
"""
        return html

    def save_html_report(
        self,
        sentiments: Dict,
        total_items: int,
        negative_items: List[Dict],
        filename: str = None
    ) -> Path:
        """
        Save HTML report to file.

        Args:
            sentiments: Sentiment counts
            total_items: Total items
            negative_items: Negative items list
            filename: Optional custom filename

        Returns:
            Path to saved HTML file
        """
        html_content = self.generate_html_content(sentiments, total_items, negative_items)

        if not filename:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"relatorio_{timestamp}.html"

        filepath = self.reports_dir / filename

        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(html_content)

        logger.info(f"HTML report saved to {filepath}")
        return filepath

    def generate_pdf_report(
        self,
        sentiments: Dict,
        total_items: int,
        negative_items: List[Dict],
        filename: str = None
    ) -> Path:
        """
        Generate PDF report from HTML.

        Args:
            sentiments: Sentiment counts
            total_items: Total items
            negative_items: Negative items list
            filename: Optional custom filename

        Returns:
            Path to saved PDF file
        """
        html_content = self.generate_html_content(sentiments, total_items, negative_items)

        if not filename:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f"relatorio_{timestamp}.pdf"

        filepath = self.reports_dir / filename

        # Font configuration for WeasyPrint
        font_config = FontConfiguration()

        # Generate PDF
        HTML(string=html_content).write_pdf(
            filepath,
            font_config=font_config
        )

        logger.info(f"PDF report saved to {filepath}")
        return filepath

    def cleanup_old_reports(self):
        """Remove old reports keeping only the most recent ones."""
        reports = sorted(
            self.reports_dir.glob('relatorio_*'),
            key=lambda p: p.stat().st_mtime,
            reverse=True
        )

        if len(reports) > settings.max_reports_stored:
            for old_report in reports[settings.max_reports_stored:]:
                old_report.unlink()
                logger.info(f"Deleted old report: {old_report.name}")
