#! /usr/bin/python3
import os
import glob
import html

def convert_txt_to_html(directory="."):
    txt_files = glob.glob(os.path.join(directory, "*.txt"))
    
    if not txt_files:
        print("Keine .txt Dateien gefunden.")
        return

    for txt_path in txt_files:
        base_name = os.path.basename(txt_path)
        file_title, _ = os.path.splitext(base_name)
        html_path = os.path.splitext(txt_path)[0] + ".html"
        
        try:
            with open(txt_path, "r", encoding="utf-8") as f:
                content = f.read()
        except UnicodeDecodeError:
            with open(txt_path, "r", encoding="latin-1") as f:
                content = f.read()
        
        escaped_content = html.escape(content)
        
        html_content = f"""<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{html.escape(file_title)}</title>
    <style>
        body {{
            font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Courier New", monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
            padding: 2em;
            max-width: 900px;
            margin: 0 auto;
            background-color: #ffffff;
            color: #1a1a1a;
            line-height: 1.5;
            font-size: 16px;
        }}
    </style>
</head>
<body>
{escaped_content}
</body>
</html>"""

        with open(html_path, "w", encoding="utf-8") as f:
            f.write(html_content)
            
        print(f"Konvertiert: {base_name} -> {os.path.basename(html_path)}")

if __name__ == "__main__":
    convert_txt_to_html()
