from pathlib import Path
from textwrap import dedent
from typing import Mapping
from md_resume_builder._core import build_pdf


class ResumeBuilder:
    _resume_section_name_to_md_file_path_mapping: Mapping[str, Path]
    _css_path: Path
    _template_html: str

    def __init__(
            self,
            resume_section_name_to_md_file_path_mapping: Mapping[str, Path],
            css_path: Path
    ) -> None:
        self._resume_section_name_to_md_file_path_mapping = resume_section_name_to_md_file_path_mapping
        self._css_path = css_path
        self._template_html = self._init_html_template()

    def build(self, output_pdf_path: Path, resume_title: str):
        self._template_html = self._template_html.replace("{{RESUME_TITLE}}", resume_title)
        build_pdf(
            self._resume_section_name_to_md_file_path_mapping,
            self._template_html,
            self._css_path,
            output_pdf_path
        )

    def _init_html_template(self) -> str:
        section_html_list = self._get_all_section_html_template()
        template_body = "\n".join(section_html_list)

        template = f'''
            <!DOCTYPE html>
            <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>{{{{RESUME_TITLE}}}}</title>
                    <link rel="stylesheet" href="{Path(self._css_path).resolve().as_uri()}">
                </head>
                <body>
                    {template_body}
                </body>
            </html>
        '''
        template = dedent(template).strip()
        return template
    
    def _get_all_section_html_template(self) -> list[str]:
        section_html_list = []
        for section_name, _ in self._resume_section_name_to_md_file_path_mapping.items():
            section_html = f'''
                <div class="{section_name}">
                    {{{{{section_name}}}}}
                </div>
            '''
            section_html = dedent(section_html).strip()
            section_html_list.append(section_html)

        return section_html_list
