"""Local-only browser cache lab. Uses memory, not project files or remote services."""

from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import parse_qs, urlsplit


class Demo(BaseHTTPRequestHandler):
    updated = False
    css_requests = 0

    def log_message(self, *args):
        pass

    def reply(self, body, content_type, cache="no-store"):
        body = body.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        self.send_header("Cache-Control", cache)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = urlsplit(self.path)
        if path.path == "/style.css":
            Demo.css_requests += 1
            color = "#167349" if Demo.updated else "#a32635"
            label = "UPDATED CSS" if Demo.updated else "INITIAL CSS"
            self.reply(
                '.sample{border-left:6px solid ' + color + ';padding:24px;background:#f4f5f6}'
                '.sample::after{content:"' + label + '";display:block;color:' + color
                + ';font-size:24px;font-weight:700;margin-top:16px}',
                "text/css; charset=utf-8", "max-age=3600",
            )
        elif path.path == "/state":
            self.reply(json.dumps({"updated": Demo.updated, "css_requests": Demo.css_requests}),
                       "application/json")
        elif path.path == "/":
            version = "2" if parse_qs(path.query).get("v") == ["2"] else "1"
            self.reply('''<!doctype html><html lang="en"><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CSS Cache Lab</title>
<style>body{font:16px/1.6 system-ui,sans-serif;color:#202124;margin:32px auto;
padding:0 20px;max-width:640px}h1{font-size:28px}a{color:#1459a0}
li{margin:14px 0}button{font:inherit;padding:6px 12px;cursor:pointer}</style>
<link rel="stylesheet" href="/style.css?v=''' + version + '''">
<h1>CSS Cache Lab</h1>
<p>HTML stylesheet URL: <code>/style.css?v=''' + version + '''</code></p>
<section class="sample"><strong>Browser-applied stylesheet</strong></section>
<ol><li><button id="update" type="button">Update server CSS</button>
<span id="status" role="status"></span></li>
<li><a href="/?step=2&amp;v=1">Open another page with the same CSS URL</a></li>
<li><a href="/?step=3&amp;v=2">Open a page with a new CSS URL</a></li></ol>
<p>Only this local demo changes. Stop with Ctrl+C; restart for a fresh server.</p>
<script>document.querySelector('#update').onclick=async()=>{
const r=await fetch('/update',{method:'POST'});
document.querySelector('#status').textContent=r.ok?' Server updated.':'';};</script>
</html>''', "text/html; charset=utf-8")
        else:
            self.send_error(404)

    def do_POST(self):
        if self.path != "/update":
            self.send_error(404)
            return
        Demo.updated = True
        self.reply('{"updated":true}', "application/json")


if __name__ == "__main__":
    with HTTPServer(("127.0.0.1", 0), Demo) as server:
        print("Open http://127.0.0.1:" + str(server.server_port) + "/", flush=True)
        print("Local cache lab only. Stop with Ctrl+C.", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass
