from pathlib import Path
import re
import os
import sys
import markdown


class MarkdownParser:
    def parse(self, text):
        sections = re.split(r"\n{3,}", text.strip())
        return "\n".join(self.parse_section(s) for s in sections)

     
    def parse_inline(self, text):
        text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)
        text = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", text)
        text = re.sub(r"\*(.*?)\*", r"<em>\1</em>", text)
        text = re.sub(r"`(.*?)`", r"<code>\1</code>", text)
        return text

    def parse_section(self, text):
        def get_sections(text):
            sections = re.split(r"\n{2,}", text.strip())
            return sections
        
        lines = get_sections(text)
        html = []

        # in_php = False
        # php_lines = []

        for line in lines:

            # if line.strip().startswith("<?php"):
            #     in_php = True
            #     php_lines.append(line)
                

            # if in_php:
            #     php_lines.append(line)

            #     if "?>" in line:
            #         html.append("\n".join(php_lines))
            #         php_lines = []
            #         in_php = False

                

            line = self.parse_inline(line)

            if line.startswith("<?php"):
                if "img" in line:
                    html.append(f"<div class='image-container'>{line}</div>")
                else:
                    html.append(line)
            elif line.startswith("# "):
                html.append(f"<h1>{line[2:]}</h1>")
            elif line.startswith("## "):
                html.append(f"<h2>{line[3:]}</h2>")
            elif line.startswith("### "):
                html.append(f"<h3>{line[4:]}</h3>")
            elif line.startswith("#### "):
                html.append(f"<h4>{line[5:]}</h4>")
            elif line.startswith("##### "):
                html.append(f"<h5>{line[6:]}</h5>")
            elif line.startswith("###### "):
                html.append(f"<h6>{line[7:]}</h6>")
            elif line.startswith("- "):
                new_line = re.sub(r"(?m)^-\s+(.*?)$", r"<li>\1</li>", line)
                html.append(f"<ul>{new_line}</ul>")
            elif line.strip():
                html.append(f"<p>{line}</p>")

        return (
            '<div class="gradient-border">\n'
            '  <div class="barvna_skatla">\n'
            + "\n".join(html)
            + "\n  </div>\n</div>"
        )





if __name__ == "__main__":
    parser = MarkdownParser()

    root = Path(__file__).parent.resolve()
    css = root / "css.css"

    md_file = Path(sys.argv[1]).resolve()
    html_file = md_file.with_suffix(".php")

    body = parser.parse(md_file.read_text(encoding="utf-8"))

    css_path = Path(
        os.path.relpath(css, html_file.parent)
    ).as_posix()

    html = f"""<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>83433121</title>
        <link rel="stylesheet" href="{css_path}">
    </head>
    <body>
    <div class="container">
    {body}
    </div>
    </body>
    </html>
    """

    html_file.write_text(html, encoding="utf-8")
    print(f"Generated {html_file}")