# -*- coding: utf-8 -*-
"""
Generates a client-presentable PDF report for a single site: traffic/search
summary, indexing status with reasons (and AI-suggested fixes where a report
has been generated), top keywords, site health, competitor snapshot, and the
full AI recommendations narrative if one exists.

Built on demand (not stored) — always reflects the current database state.
"""
import io
import re
from datetime import datetime

from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import (
    BaseDocTemplate, PageTemplate, Frame, Paragraph, Spacer, PageBreak,
    Table, TableStyle, ListFlowable, ListItem, HRFlowable
)

INK = colors.HexColor('#1A2330')
MUTED = colors.HexColor('#5B6B7C')
FAINT = colors.HexColor('#93A2B0')
TEAL = colors.HexColor('#0F7A63')
TEAL_DARK = colors.HexColor('#0B5C4B')
RED = colors.HexColor('#B23A3A')
GREEN = colors.HexColor('#1F8A5F')
RULE = colors.HexColor('#D7DEE4')
PANEL = colors.HexColor('#F5F7F8')

PAGE_W, PAGE_H = letter
MARGIN = 0.8 * inch

_styles = {
    'CoverTitle': ParagraphStyle('RepCoverTitle', fontName='Helvetica-Bold', fontSize=26,
                                  leading=30, textColor=INK, spaceAfter=6),
    'CoverSub': ParagraphStyle('RepCoverSub', fontName='Helvetica', fontSize=13,
                                leading=18, textColor=TEAL_DARK, spaceAfter=4),
    'CoverMeta': ParagraphStyle('RepCoverMeta', fontName='Helvetica', fontSize=9.5,
                                 leading=14, textColor=MUTED),
    'H1': ParagraphStyle('RepH1', fontName='Helvetica-Bold', fontSize=15, leading=19,
                          textColor=INK, spaceBefore=4, spaceAfter=10),
    'H2': ParagraphStyle('RepH2', fontName='Helvetica-Bold', fontSize=11.5, leading=15,
                          textColor=TEAL_DARK, spaceBefore=12, spaceAfter=6),
    'H3': ParagraphStyle('RepH3', fontName='Helvetica-Bold', fontSize=10, leading=13,
                          textColor=INK, spaceBefore=8, spaceAfter=4),
    'Body': ParagraphStyle('RepBody', fontName='Helvetica', fontSize=9.5, leading=14,
                            textColor=INK, spaceAfter=7, alignment=TA_LEFT),
    'BodyMuted': ParagraphStyle('RepBodyMuted', fontName='Helvetica', fontSize=9,
                                 leading=13, textColor=MUTED, spaceAfter=7),
    'Bullet': ParagraphStyle('RepBullet', fontName='Helvetica', fontSize=9.5, leading=13.5,
                              textColor=INK, spaceAfter=4),
    'CellHead': ParagraphStyle('RepCellHead', fontName='Helvetica-Bold', fontSize=8.3,
                                leading=10.5, textColor=colors.white),
    'Cell': ParagraphStyle('RepCell', fontName='Helvetica', fontSize=8.3, leading=11.5,
                            textColor=INK),
    'CellMuted': ParagraphStyle('RepCellMuted', fontName='Helvetica', fontSize=8,
                                 leading=11, textColor=MUTED),
    'Caption': ParagraphStyle('RepCaption', fontName='Helvetica-Oblique', fontSize=8,
                               leading=11, textColor=FAINT),
}


def _esc(text):
    if text is None:
        return ''
    text = str(text)
    return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')


def _inline(text):
    text = _esc(text)
    text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)
    return text


def _markdown_to_flowables(md_text):
    flowables = []
    bullets = []

    def flush():
        nonlocal bullets
        if bullets:
            flowables.append(ListFlowable(
                [ListItem(Paragraph(_inline(b), _styles['Bullet']), spaceAfter=3) for b in bullets],
                bulletType='bullet', start='•', leftIndent=14
            ))
            flowables.append(Spacer(1, 4))
            bullets = []

    for raw_line in (md_text or '').split('\n'):
        line = raw_line.rstrip()
        stripped = line.strip()
        if not stripped:
            flush()
            continue
        if stripped.startswith('## '):
            flush()
            flowables.append(Paragraph(_inline(stripped[3:]), _styles['H2']))
        elif stripped.startswith('### '):
            flush()
            flowables.append(Paragraph(_inline(stripped[4:]), _styles['H3']))
        elif stripped.startswith('- ') or stripped.startswith('* '):
            bullets.append(stripped[2:].strip())
        else:
            flush()
            flowables.append(Paragraph(_inline(stripped), _styles['Body']))
    flush()
    return flowables


class ReportDoc(BaseDocTemplate):
    def __init__(self, filename_or_buffer, site_name, **kw):
        self.site_name = site_name
        super().__init__(filename_or_buffer, **kw)

    def _header_footer(self, canvas, doc):
        canvas.saveState()
        canvas.setStrokeColor(RULE)
        canvas.setLineWidth(0.6)
        if doc.page > 1:
            canvas.line(MARGIN, PAGE_H - 0.5 * inch, PAGE_W - MARGIN, PAGE_H - 0.5 * inch)
            canvas.setFont('Helvetica', 7.5)
            canvas.setFillColor(FAINT)
            canvas.drawString(MARGIN, PAGE_H - 0.42 * inch, f'SEO Report — {self.site_name}')
            canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.42 * inch,
                                    datetime.now().strftime('%d %b %Y'))
            canvas.line(MARGIN, 0.55 * inch, PAGE_W - MARGIN, 0.55 * inch)
            canvas.drawRightString(PAGE_W - MARGIN, 0.38 * inch, f'{doc.page}')
        canvas.restoreState()


def _ref_table(header, rows, col_widths, header_bg=TEAL):
    data = [[Paragraph(h, _styles['CellHead']) for h in header]]
    for r in rows:
        data.append([Paragraph(_esc(c), _styles['Cell']) for c in r])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), header_bg),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, PANEL]),
        ('GRID', (0, 0), (-1, -1), 0.5, RULE),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 5),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
    ]))
    return t


def _metric_grid(items):
    """items: list of (value_str, label_str, color)"""
    cells = []
    for val, label, color in items:
        cell_style = ParagraphStyle('m', fontName='Helvetica-Bold', fontSize=18,
                                     textColor=color, alignment=TA_CENTER, leading=22)
        label_style = ParagraphStyle('ml', fontName='Helvetica', fontSize=7.5,
                                      textColor=MUTED, alignment=TA_CENTER, leading=10)
        inner = Table([[Paragraph(_esc(val), cell_style)], [Paragraph(_esc(label), label_style)]])
        inner.setStyle(TableStyle([
            ('TOPPADDING', (0, 0), (-1, 0), 10), ('BOTTOMPADDING', (0, 0), (-1, 0), 2),
            ('BOTTOMPADDING', (0, 1), (-1, 1), 10),
        ]))
        cells.append(inner)
    width = (PAGE_W - 2 * MARGIN) / len(cells)
    grid = Table([cells], colWidths=[width] * len(cells))
    grid.setStyle(TableStyle([
        ('BOX', (0, 0), (-1, -1), 0.75, RULE),
        ('INNERGRID', (0, 0), (-1, -1), 0.5, RULE),
        ('BACKGROUND', (0, 0), (-1, -1), PANEL),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ]))
    return grid


def generate_site_report_pdf(site, period_days, traffic_totals, indexed_pages, keywords,
                              latest_health, latest_psi, competitor_rows, ai_recommendation):
    """
    Returns PDF bytes for the given site's report.

    traffic_totals: dict with sessions, gsc_clicks, gsc_impressions, gsc_avg_position
    latest_health: HealthCheck instance or None
    latest_psi: PSIScore instance or None
    competitor_rows: list of (Competitor, CompetitorSnapshot|None)
    ai_recommendation: AIRecommendation instance or None
    """
    buf = io.BytesIO()
    doc = ReportDoc(buf, site.name, pagesize=letter,
                     topMargin=1.0 * inch, bottomMargin=0.85 * inch,
                     leftMargin=MARGIN, rightMargin=MARGIN,
                     title=f'SEO Report — {site.name}')
    frame = Frame(MARGIN, doc.bottomMargin, PAGE_W - 2 * MARGIN,
                   PAGE_H - doc.topMargin - doc.bottomMargin, id='normal')
    doc.addPageTemplates([PageTemplate(id='normal', frames=[frame], onPage=doc._header_footer)])

    story = []

    # ---------------------------------------------------------- cover
    story.append(Spacer(1, 0.9 * inch))
    story.append(HRFlowable(width='100%', thickness=2, color=TEAL, spaceAfter=16))
    story.append(Paragraph('SEO Performance Report', _styles['CoverTitle']))
    story.append(Paragraph(_esc(site.name), _styles['CoverSub']))
    story.append(Spacer(1, 4))
    story.append(Paragraph(_esc(site.url), ParagraphStyle('url', fontName='Courier', fontSize=9,
                                                            textColor=TEAL_DARK)))
    story.append(Spacer(1, 18))
    cover_rows = [
        ['Client', site.project.client.name],
        ['Project', site.project.name],
        ['Reporting period', f'Last {period_days} days'],
        ['Generated', datetime.now().strftime('%d %B %Y')],
    ]
    cover_table = Table(
        [[Paragraph(f'<b>{_esc(a)}</b>', _styles['CoverMeta']), Paragraph(_esc(b), _styles['CoverMeta'])]
         for a, b in cover_rows],
        colWidths=[1.5 * inch, 4.3 * inch]
    )
    cover_table.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 3), ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
    ]))
    story.append(cover_table)
    story.append(Spacer(1, 30))

    story.append(Paragraph('At a glance', _styles['H2']))
    not_indexed_count = sum(1 for p in indexed_pages if p.verdict != 'PASS')
    story.append(_metric_grid([
        (str(traffic_totals.get('sessions', '—')), 'Sessions', INK),
        (str(traffic_totals.get('gsc_clicks', '—')), 'GSC clicks', INK),
        (str(not_indexed_count), 'Pages not indexed', RED if not_indexed_count else GREEN),
        (str(latest_psi.performance) if latest_psi and latest_psi.performance is not None else '—',
         'PSI mobile score', INK),
    ]))
    story.append(PageBreak())

    # ---------------------------------------------------------- search & traffic
    story.append(Paragraph('Search &amp; traffic summary', _styles['H1']))
    story.append(_ref_table(
        ['Metric', 'Value'],
        [
            ['Sessions (GA4)', traffic_totals.get('sessions', '—')],
            ['Active users (GA4)', traffic_totals.get('active_users', '—')],
            ['Clicks (Search Console)', traffic_totals.get('gsc_clicks', '—')],
            ['Impressions (Search Console)', traffic_totals.get('gsc_impressions', '—')],
            ['Average position (Search Console)', traffic_totals.get('gsc_avg_position', '—')],
        ],
        [3.2 * inch, 2.6 * inch]
    ))
    story.append(Spacer(1, 8))

    if keywords:
        story.append(Paragraph('Top search queries', _styles['H2']))
        story.append(_ref_table(
            ['Query', 'Clicks', 'Impressions', 'CTR', 'Avg. position'],
            [[k.search_query, k.clicks, k.impressions, f'{k.ctr}%', k.position] for k in keywords[:15]],
            [2.6 * inch, 0.9 * inch, 1.1 * inch, 0.8 * inch, 1.2 * inch]
        ))
    story.append(PageBreak())

    # ---------------------------------------------------------- indexing
    story.append(Paragraph('Indexing status', _styles['H1']))
    story.append(Paragraph(
        (f'{len(indexed_pages) - not_indexed_count} of {len(indexed_pages)} inspected pages are indexed '
         f'normally.') if indexed_pages else 'No pages have been inspected yet.',
        _styles['BodyMuted']
    ))
    if indexed_pages:
        story.append(_ref_table(
            ['URL', 'Status', 'Reason'],
            [[p.url, (p.verdict or 'UNKNOWN'), (p.reason or '—')] for p in indexed_pages],
            [2.4 * inch, 0.9 * inch, 2.5 * inch]
        ))
    story.append(PageBreak())

    # ---------------------------------------------------------- health & psi
    story.append(Paragraph('Technical &amp; mobile health', _styles['H1']))
    if latest_health:
        health_rows = [
            ['HTTP status', latest_health.http_status],
            ['Response time', f'{latest_health.response_time_ms}ms'],
            ['Title / meta description present', f'{"Yes" if latest_health.has_title else "No"} / '
             f'{"Yes" if latest_health.has_meta_description else "No"}'],
            ['H1 count', latest_health.h1_count],
            ['Word count', latest_health.word_count],
            ['Viewport meta tag', 'Yes' if latest_health.has_viewport_meta else 'No'],
            ['CSS breakpoints detected', latest_health.media_query_count],
            ['Broken internal links', latest_health.broken_links_count],
            ['robots.txt reachable / sitemap.xml found', f'{"Yes" if latest_health.robots_txt_ok else "No"} / '
             f'{"Yes" if latest_health.sitemap_found else "No"}'],
        ]
        story.append(_ref_table(['Signal', 'Value'], health_rows, [3.2 * inch, 2.6 * inch]))
    else:
        story.append(Paragraph('No health check has been run yet.', _styles['BodyMuted']))

    if latest_psi:
        story.append(Spacer(1, 10))
        story.append(Paragraph('PageSpeed Insights (mobile)', _styles['H2']))
        story.append(_ref_table(
            ['Performance', 'Accessibility', 'Best practices', 'SEO', 'LCP', 'CLS'],
            [[latest_psi.performance, latest_psi.accessibility, latest_psi.best_practices,
              latest_psi.seo, f'{latest_psi.lcp}s' if latest_psi.lcp else '—',
              latest_psi.cls if latest_psi.cls is not None else '—']],
            [0.95 * inch] * 6
        ))
    story.append(PageBreak())

    # ---------------------------------------------------------- competitors
    if competitor_rows:
        story.append(Paragraph('Competitor benchmark', _styles['H1']))
        rows = [['Us', site.name, latest_health.word_count if latest_health else '—',
                 latest_health.h1_count if latest_health else '—',
                 'Yes' if latest_health and latest_health.has_viewport_meta else 'No',
                 latest_psi.performance if latest_psi and latest_psi.performance is not None else '—']]
        for comp, snap in competitor_rows:
            rows.append([
                'Comp', comp.url,
                snap.word_count if snap else '—', snap.h1_count if snap else '—',
                ('Yes' if snap.has_viewport_meta else 'No') if snap else '—',
                snap.psi_performance if snap and snap.psi_performance is not None else '—',
            ])
        story.append(_ref_table(
            ['', 'Site', 'Words', 'H1s', 'Viewport', 'PSI perf'],
            rows, [0.5 * inch, 2.3 * inch, 0.7 * inch, 0.6 * inch, 0.8 * inch, 0.8 * inch]
        ))
        story.append(PageBreak())

    # ---------------------------------------------------------- AI recommendations
    story.append(Paragraph('Recommendations', _styles['H1']))
    if ai_recommendation:
        story.append(Paragraph(
            f'Generated {ai_recommendation.generated_at.strftime("%d %b %Y")} using '
            f'{ai_recommendation.model_used or "AI"} — based on the data in this report.',
            _styles['Caption']
        ))
        story.append(Spacer(1, 6))
        story.extend(_markdown_to_flowables(ai_recommendation.content))
    else:
        story.append(Paragraph(
            'No AI recommendations have been generated for this site yet. Generate one from the '
            'site\u2019s page in the dashboard to include specific, data-driven fixes here.',
            _styles['BodyMuted']
        ))

    doc.multiBuild(story)
    buf.seek(0)
    return buf.getvalue()
