"""Convert a Markdown file to PDF using the `markdown` package + Edge headless.

Usage:
    python md_to_pdf.py <input.md> <output.pdf>

Designed for Windows where pandoc/wkhtmltopdf may not be installed but Edge is.
"""
import markdown
import subprocess
import os
import sys
import tempfile

if len(sys.argv) != 3:
    print('Usage: python md_to_pdf.py <input.md> <output.pdf>')
    sys.exit(2)

input_md, output_pdf = sys.argv[1], sys.argv[2]

with open(input_md, 'r', encoding='utf-8') as f:
    md_content = f.read()

html_body = markdown.markdown(md_content, extensions=['tables', 'fenced_code', 'sane_lists'])

html = """<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Close Checklist Template v1</title>
<style>
@page { size: Letter; margin: 0.5in 0.6in; }
body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a1a; line-height: 1.5; font-size: 10.5pt; }
h1 { color: #1A7A3E; border-bottom: 3px solid #25A354; padding-bottom: 8px; }
h2 { color: #25A354; border-bottom: 1px solid #ccc; padding-bottom: 4px; margin-top: 28px; page-break-after: avoid; }
h3 { color: #C76A1F; margin-top: 20px; page-break-after: avoid; }
table { border-collapse: collapse; width: 100%; margin: 12px 0; page-break-inside: auto; }
tr { page-break-inside: avoid; }
th { background: #25A354; color: white; padding: 8px; text-align: left; border: 1px solid #1A7A3E; font-size: 10pt; }
td { padding: 6px 8px; border: 1px solid #ccc; vertical-align: top; font-size: 10pt; }
tr:nth-child(even) td { background: #f7f7f7; }
code { background: #f0f0f0; padding: 2px 4px; border-radius: 3px; font-family: 'Consolas', 'Courier New', monospace; font-size: 9.5pt; }
pre { background: #2d2d2d; color: #d4d4d4; padding: 12px; border-radius: 4px; overflow-x: auto; font-size: 9pt; page-break-inside: avoid; }
pre code { background: transparent; padding: 0; color: inherit; }
blockquote { border-left: 4px solid #FFA333; padding-left: 12px; color: #444; margin: 12px 0; }
hr { border: none; border-top: 2px solid #ddd; margin: 24px 0; }
strong { color: #1A7A3E; }
ul, ol { padding-left: 24px; }
li { margin: 4px 0; }
</style></head><body>
""" + html_body + "</body></html>"

tf = tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False, encoding='utf-8')
tf.write(html)
tf.close()

edge = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
file_url = 'file:///' + tf.name.replace('\\', '/')

result = subprocess.run([
    edge,
    '--headless=new',
    '--disable-gpu',
    '--no-pdf-header-footer',
    '--print-to-pdf=' + output_pdf,
    file_url,
], capture_output=True, text=True, timeout=60)

os.unlink(tf.name)

if not os.path.exists(output_pdf):
    print('FAILED:', result.stderr or result.stdout)
    sys.exit(1)

print('OK:', output_pdf, f'({os.path.getsize(output_pdf):,} bytes)')
