import csv
from io import BytesIO

from django.http import HttpResponse
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet

from openpyxl import Workbook


# =====================================================
# 🔹 PDF EXPORT
# =====================================================

def export_pdf(report_data, title="Report"):
    buffer = BytesIO()

    doc = SimpleDocTemplate(buffer)
    styles = getSampleStyleSheet()

    elements = []

    elements.append(Paragraph(title, styles["Title"]))
    elements.append(Spacer(1, 12))

    for key, value in report_data.items():
        elements.append(Paragraph(f"{key}: {value}", styles["Normal"]))
        elements.append(Spacer(1, 8))

    doc.build(elements)

    buffer.seek(0)

    response = HttpResponse(buffer, content_type="application/pdf")
    response["Content-Disposition"] = f'attachment; filename="{title}.pdf"'

    return response


# =====================================================
# 🔹 EXCEL EXPORT
# =====================================================

def export_excel(report_data, title="Report"):
    wb = Workbook()
    ws = wb.active
    ws.title = title

    # Header
    ws.append(["Metric", "Value"])

    for key, value in report_data.items():
        ws.append([key, value])

    response = HttpResponse(
        content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )
    response["Content-Disposition"] = f'attachment; filename="{title}.xlsx"'

    wb.save(response)

    return response


# =====================================================
# 🔹 CSV EXPORT
# =====================================================

def export_csv(report_data, title="Report"):
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = f'attachment; filename="{title}.csv"'

    writer = csv.writer(response)
    writer.writerow(["Metric", "Value"])

    for key, value in report_data.items():
        writer.writerow([key, value])

    return response