import hashlib
import json
import os
from pathlib import Path
import tempfile
from xml.sax.saxutils import escape


JD_FOLDER = Path(
    "/home/kineticcosmos/kineticcosmospython.com/"
    "kinetic-cosmos-api/uploads/job_descriptions"
)

JD_FOLDER.mkdir(parents=True, exist_ok=True)


def create_jd_pdf(job, description):
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer

    content = json.dumps({"job": job, "description": description, "layout": 1},
                         sort_keys=True, ensure_ascii=False)
    digest = hashlib.sha256(content.encode("utf-8")).hexdigest()[:24]
    filename = f"hrms-jd-{job['id']}-{digest}.pdf"
    JD_FOLDER.mkdir(parents=True, exist_ok=True)
    target = JD_FOLDER / filename
    print("PDF GENERATION PATH:", target.resolve())
    if target.is_file():
        return filename

    styles = getSampleStyleSheet()
    styles["Title"].textColor = colors.HexColor("#0f172a")
    styles["BodyText"].leading = 16
    story = [Paragraph("Kinetic Cosmos", styles["Heading2"]),
             Paragraph(escape(job["job_title"]), styles["Title"]), Spacer(1, 14)]
    for field, label in (("department", "Department"), ("location", "Location"),
                         ("employment_type", "Employment Type"), ("work_mode", "Work Mode"),
                         ("experience", "Experience"), ("salary", "Salary")):
        if job.get(field):
            story.append(Paragraph(f"<b>{label}:</b> {escape(job[field])}", styles["BodyText"]))
    story.append(Spacer(1, 16))
    for block in description.split("\n\n"):
        if block.strip():
            story.append(Paragraph(escape(block).replace("\n", "<br/>"), styles["BodyText"]))
            story.append(Spacer(1, 10))

    # Publish a complete file atomically; the database never points at a partial PDF.
    handle, temporary = tempfile.mkstemp(suffix=".pdf", dir=JD_FOLDER)
    os.close(handle)
    try:
        SimpleDocTemplate(temporary, pagesize=A4, rightMargin=42, leftMargin=42,
                          topMargin=42, bottomMargin=42).build(story)
        os.replace(temporary, target)
    finally:
        Path(temporary).unlink(missing_ok=True)
    return filename