#!/usr/bin/env python3
"""
Dev server for The Web Platform Can Do That?!

Static files plus exactly ONE server-side program: /convert, the round-trip
half of the Unbreakable Page demo (just-whatever/unbreakable.html).
Zero packages here too — this is the Python standard library only.

    python3 serve.py            # http://localhost:8735/
    python3 serve.py 9000       # custom port
"""
import sys
import html
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

STRINGS = {
    "en": {"dir": "ltr", "title": "Server says",
           "computed": "Computed on the server — no JavaScript was involved.",
           "bad": "is not a temperature. Server-side validation says no (Module 06 sends its regards).",
           "back": "← Back to the article"},
    "es": {"dir": "ltr", "title": "El servidor dice",
           "computed": "Calculado en el servidor — sin JavaScript.",
           "bad": "no es una temperatura. La validación del servidor dice que no.",
           "back": "← Volver al artículo"},
    "ar": {"dir": "rtl", "title": "يقول الخادم",
           "computed": "حُسبت النتيجة على الخادم — دون جافاسكربت.",
           "bad": "ليست درجة حرارة. تحقق الخادم يرفضها.",
           "back": "→ العودة إلى المقال"},
}


class Handler(SimpleHTTPRequestHandler):
    def do_GET(self):
        url = urlparse(self.path)
        if url.path != "/convert":
            return super().do_GET()

        qs = parse_qs(url.query)
        raw = qs.get("c", [""])[0]
        lang = qs.get("lang", ["en"])[0]
        s = STRINGS.get(lang, STRINGS["en"])
        back = self.headers.get("Referer") or "/just-whatever/unbreakable-article.html"

        try:
            c = float(raw)
            result = f"{c:g} °C = {c * 9 / 5 + 32:g} °F"
            note = s["computed"]
        except ValueError:
            result = f"“{html.escape(raw)}”"
            note = s["bad"]

        body = f"""<!DOCTYPE html>
<html lang="{html.escape(lang)}" dir="{s['dir']}">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{s['title']}</title></head>
<body style="font-family: Georgia, serif; background: #f7f5f0; color: #2a2a24;
             display: grid; place-items: center; min-height: 100vh; margin: 0; text-align: center;">
<main>
    <p style="font-size: clamp(1.6rem, 6vw, 2.6rem); font-weight: bold; margin: 0 0 0.4em;">{result}</p>
    <p style="color: #6b6656;">{note}</p>
    <p><a href="{html.escape(back, quote=True)}" style="color: #23402e;">{s['back']}</a></p>
</main>
</body></html>"""
        payload = body.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8735
    print(f"The Web Platform Can Do That?! → http://localhost:{port}/  (Ctrl+C stops)")
    ThreadingHTTPServer(("", port), Handler).serve_forever()
