from pathlib import Path

import frontmatter  # pyright: ignore[reportMissingTypeStubs]
import markdown
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML  # pyright: ignore[reportMissingTypeStubs]

from .models import CVData

SRC_DIR = Path(__file__).resolve().parent


def generate_pdf(input_file: Path, output_file: Path | None = None) -> Path:
    post = frontmatter.load(str(input_file))

    cv = CVData.model_validate(post.metadata)
    letter_body: str = markdown.markdown(post.content)

    input_dir = Path(input_file).resolve().parent
    cv.photo = str(input_dir / cv.photo)
    cv.signature = str(input_dir / cv.signature)

    env = Environment(loader=FileSystemLoader(str(SRC_DIR)))
    template = env.get_template("cv.html.j2")

    html_str = template.render(cv=cv, letter_body=letter_body)

    if output_file is None:
        output_file = input_file.with_suffix(".pdf")

    _ = HTML(string=html_str, base_url=str(SRC_DIR)).write_pdf(output_file)  # pyright: ignore[reportUnknownMemberType]
    return output_file
