"""Audit trail export generator — tamper-evident PDF/JSON from SQLite history."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from apiposture_pro.features.historical_tracking.models import ScanRecord


def _record_to_export_dict(record: ScanRecord) -> dict[str, Any]:
    """Convert a ScanRecord to the canonical export dict (sorted keys)."""
    return {
        "checksum": getattr(record, "checksum", None) or "",
        "critical_count": record.critical_count,
        "findings_json": record.findings_json or "",
        "git_branch": record.git_branch,
        "git_commit": record.git_commit,
        "git_is_dirty": record.git_is_dirty,
        "high_count": record.high_count,
        "id": record.id,
        "info_count": record.info_count,
        "low_count": record.low_count,
        "medium_count": record.medium_count,
        "operator": getattr(record, "operator", None),
        "project_path": record.project_path,
        "risk_score": record.risk_score,
        "scan_duration_ms": record.scan_duration_ms,
        "scan_time": record.scan_time.isoformat() if record.scan_time else None,
        "tags": record.tags,
        "total_endpoints": record.total_endpoints,
        "total_findings": record.total_findings,
    }


def generate_json_export(record: ScanRecord, output_path: Path) -> None:
    """Write canonical JSON export with checksum field."""
    data = _record_to_export_dict(record)
    # Canonical: sorted keys, no whitespace
    canonical = json.dumps(data, sort_keys=True, separators=(",", ":"))
    output_path.write_text(canonical, encoding="utf-8")


def generate_pdf_export(record: ScanRecord, output_path: Path) -> None:
    """Write audit trail PDF export with checksum in footer."""
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    from reportlab.lib.units import cm
    from reportlab.platypus import (
        HRFlowable,
        Paragraph,
        SimpleDocTemplate,
        Spacer,
        Table,
        TableStyle,
    )

    doc = SimpleDocTemplate(
        str(output_path),
        pagesize=A4,
        rightMargin=2 * cm,
        leftMargin=2 * cm,
        topMargin=2 * cm,
        bottomMargin=2 * cm,
    )
    styles = getSampleStyleSheet()
    story = []

    title_style = ParagraphStyle(
        "AuditTitle", parent=styles["Title"], fontSize=18, spaceAfter=12
    )
    story.append(Paragraph("Audit Trail Export", title_style))
    story.append(Paragraph("ApiPosturePro — Tamper-Evident Scan Record", styles["Normal"]))
    story.append(Spacer(1, 0.4 * cm))

    story.append(Paragraph("Scan Record", styles["Heading2"]))
    story.append(HRFlowable(width="100%"))
    story.append(Spacer(1, 0.2 * cm))

    meta_rows = [
        ["Field", "Value"],
        ["ID", str(record.id)],
        ["Project Path", record.project_path],
        ["Scan Time", record.scan_time.isoformat() if record.scan_time else "—"],
        ["Total Endpoints", str(record.total_endpoints)],
        ["Total Findings", str(record.total_findings)],
        ["Risk Score", str(record.risk_score)],
        ["Git Branch", record.git_branch or "—"],
        ["Git Commit", record.git_commit or "—"],
        ["Operator", getattr(record, "operator", None) or "—"],
    ]

    meta_table = Table(meta_rows, colWidths=[4 * cm, 12 * cm])
    meta_table.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#2c3e50")),
                ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
                ("FONTSIZE", (0, 0), (-1, -1), 9),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
                ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f9f9f9")]),
            ]
        )
    )
    story.append(meta_table)
    story.append(Spacer(1, 0.4 * cm))

    # Severity breakdown
    story.append(Paragraph("Severity Breakdown", styles["Heading2"]))
    story.append(HRFlowable(width="100%"))
    story.append(Spacer(1, 0.2 * cm))
    sev_rows = [
        ["Critical", str(record.critical_count)],
        ["High", str(record.high_count)],
        ["Medium", str(record.medium_count)],
        ["Low", str(record.low_count)],
        ["Info", str(record.info_count)],
    ]
    sev_table = Table(sev_rows, colWidths=[4 * cm, 4 * cm])
    sev_table.setStyle(
        TableStyle(
            [
                ("FONTSIZE", (0, 0), (-1, -1), 9),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
                ("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.white, colors.HexColor("#f9f9f9")]),
            ]
        )
    )
    story.append(sev_table)
    story.append(Spacer(1, 0.6 * cm))

    # Footer with checksum
    footer_style = ParagraphStyle(
        "AuditFooter", parent=styles["Normal"], fontSize=8, textColor=colors.grey
    )
    story.append(HRFlowable(width="100%"))
    checksum = getattr(record, "checksum", None) or "—"
    story.append(Paragraph(f"Checksum (SHA-256): {checksum}", footer_style))
    story.append(Paragraph("Generated by ApiPosturePro Audit Trail Export", footer_style))

    doc.build(story)
