#!/usr/bin/env python3
import http.server
import socketserver
import os
from pathlib import Path

PORT = 8080

class GameHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Wenn die Wurzel angefordert wird, serviere index.php als HTML
        if self.path == '/' or self.path == '/index.php':
            self.path = '/index.html'
        
        # Versuche die Datei zu servieren
        try:
            return super().do_GET()
        except:
            self.send_error(404)

    def end_headers(self):
        # Verhindere Caching für dynamische Inhalte
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        super().end_headers()

# Konvertiere index.php zu index.html für diesen Server
os.chdir('/home/ubuntu/gamification_web')

# Lese die PHP-Datei und konvertiere sie zu HTML
with open('index.php', 'r', encoding='utf-8') as f:
    php_content = f.read()

# Entferne PHP-Tags und führe die PHP-Logik aus
html_content = php_content.replace('<?php', '').replace('?>', '')

# Schreibe als HTML-Datei
with open('index.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

with socketserver.TCPServer(("", PORT), GameHandler) as httpd:
    print(f"Server läuft auf Port {PORT}")
    print(f"Öffne http://localhost:{PORT} in deinem Browser")
    httpd.serve_forever()
