import hashlib
import os
from pathlib import Path
import tempfile
from urllib.parse import urlparse
from urllib.request import urlopen
from fastapi import HTTPException
from careers_config import JD_FOLDER


def create_jd_pdf(job, description):
    url = job.get("pdf_url")
    parsed = urlparse(url or "")
    if (parsed.scheme != "https" or parsed.netloc != "api-hrms.kineticcosmos.in"
            or parsed.path != f"/public/careers/jobs/{job['id']}/pdf"):
        raise HTTPException(503, "Invalid HRMS PDF link")
    with urlopen(url, timeout=20) as response:
        data = response.read(20 * 1024 * 1024 + 1)
    if len(data) > 20 * 1024 * 1024 or not data.startswith(b"%PDF-"):
        raise HTTPException(503, "HRMS did not return a valid PDF")
    name = f"hrms-styled-{job['id']}-{hashlib.sha256(data).hexdigest()[:24]}.pdf"
    JD_FOLDER.mkdir(parents=True, exist_ok=True)
    target = JD_FOLDER / name
    if target.is_file():
        os.chmod(target, 0o644)
    else:
        descriptor, temporary = tempfile.mkstemp(dir=JD_FOLDER, suffix=".pdf")
        try:
            with os.fdopen(descriptor, "wb") as output:
                output.write(data)
            os.chmod(temporary, 0o644)
            os.replace(temporary, target)
        finally:
            Path(temporary).unlink(missing_ok=True)
    return name