from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from jinja2 import Template

from trame import Trame


# Configuration
MARKDOWN_FILE = Path(__file__).parent.parent / "data" / "dummy.md"
PORT = 8000


def main():
    """Start the server with hardcoded configuration"""
    Handler = factory_handler(MARKDOWN_FILE)
    server = HTTPServer(("localhost", PORT), Handler)
    print(f"Server running at http://localhost:{PORT}")
    print(f"Serving file: {MARKDOWN_FILE}")
    server.serve_forever()


def factory_handler(markdown_path):
    """Factory function to create handler with markdown_path in closure"""

    class RequestHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            # Load the trame file
            trame = Trame.from_file(markdown_path)

            # Render template
            template = factory_template()
            html = template.render(trame=trame)

            # Send response
            self.send_response(200)
            self.send_header("Content-type", "text/html; charset=utf-8")
            self.end_headers()
            self.wfile.write(html.encode("utf-8"))

    return RequestHandler


def factory_template():
    """Create Jinja2 template with basic styling"""
    template_str = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Trame Viewer</title>
    <style>
        body {
            font-family: system-ui, -apple-system, sans-serif;
            max-width: 800px;
            margin: 0 auto;
        }
        h1 {
            background-color: #F0EEF7;
            padding: 10px;
        }

    </style>
</head>
<body>
    <h1>{{ trame.path }}</h1>
    <hr>
    
    {% for piece in trame.pieces %}
    <div class="piece">
    
        {{ piece.html | safe }}
    </div>
    {% endfor %}
</body>
</html>
"""
    return Template(template_str)


if __name__ == "__main__":
    main()
