from markdown import markdown
from pathlib import Path
from typing import Mapping
from weasyprint import CSS, HTML


def inject_data_into_template(
    template_html: str, markdown_data: Mapping[str, str]
) -> HTML:
    for section_name, section_data_raw in markdown_data.items():
        section_data_html: str = markdown(section_data_raw)
        placeholder = f"{{{{{section_name}}}}}"
        template_html = template_html.replace(placeholder, section_data_html)

    final_html: HTML = HTML(string=template_html)
    return final_html


def read_md_file(file_path: Path) -> str:
    markdown_data = file_path.read_text()
    return markdown_data


def build_pdf(
    resume_section_name_to_md_file_path_mapping: Mapping[str, Path],
    template_html: str,
    css_path: Path,
    output_pdf_path: Path
) -> None:
    markdown_data: dict[str, str] = {}
    for resume_section_name, md_file_path in resume_section_name_to_md_file_path_mapping.items():
        markdown_data[resume_section_name] = read_md_file(md_file_path)
    final_html: HTML = inject_data_into_template(template_html, markdown_data)
    final_html.write_pdf(output_pdf_path, stylesheets=[CSS(filename=css_path)])
