from jinja2 import Environment, FileSystemLoader
from playwright.sync_api import sync_playwright

from context import context_list

env = Environment(loader=FileSystemLoader("report_gen"))

html_pages = []

for i, context in enumerate(context_list):
    template = env.get_template(f"page_{i + 1}.html")
    html_pages.append(template.render(context))

# Combine with page breaks
final_html = "<div class='page-break'></div>".join(html_pages)
# Wrap in full HTML document
html_doc = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet">
  <style>
    html, body {{
        height: 100%;
        margin: 0;
        padding: 0;
    }}
    .page-break {{ page-break-after: always; }}
    .page {{
      height: 100%;
    }}
      /* Reset margins and padding everywhere */
  * {{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }}

  </style>
</head>
<body class="m-0 p-0">
  {final_html}
</body>
</html>
"""


# Generate PDF


def html_string_to_pdf(html_content, pdf_path):
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        # Set the HTML directly
        page.set_content(html_content)

        # Export to PDF
        page.pdf(path=pdf_path, format="A4", print_background=True)

        browser.close()


html_string_to_pdf(html_doc, "multi_page_report.pdf")
# pdfkit.from_string(html_doc, "truth_report.pdf", options=options)

print("✅ PDF generated: multi_page_report.pdf")
