#!/usr/bin/env python3
"""Static server for the Chai Zebra site with HTTP Range support (needed for
smooth audio seeking in the teaser). Serves the project dir on 127.0.0.1:6700."""
import http.server, os, re, sys

PORT = 6700

class RangeHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # dev server: never cache, so every reload shows the latest edit
        self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
        self.send_header("Pragma", "no-cache")
        super().end_headers()

    def copyfile(self, source, outputfile):
        n = getattr(self, "_copylen", None)
        if n is None:
            return super().copyfile(source, outputfile)
        remaining = n
        while remaining > 0:
            chunk = source.read(min(65536, remaining))
            if not chunk:
                break
            outputfile.write(chunk)
            remaining -= len(chunk)

    def send_head(self):
        self._copylen = None
        rng = self.headers.get("Range")
        path = self.translate_path(self.path)
        if rng and os.path.isfile(path):
            try:
                f = open(path, "rb")
            except OSError:
                self.send_error(404)
                return None
            size = os.fstat(f.fileno()).st_size
            m = re.match(r"bytes=(\d*)-(\d*)$", rng.strip())
            if m:
                s = int(m.group(1)) if m.group(1) else 0
                e = int(m.group(2)) if m.group(2) else size - 1
                e = min(e, size - 1)
                if 0 <= s <= e < size:
                    length = e - s + 1
                    self.send_response(206)
                    self.send_header("Content-Type", self.guess_type(path))
                    self.send_header("Accept-Ranges", "bytes")
                    self.send_header("Content-Range", f"bytes {s}-{e}/{size}")
                    self.send_header("Content-Length", str(length))
                    self.end_headers()
                    f.seek(s)
                    self._copylen = length
                    return f
            f.close()
        return super().send_head()

if __name__ == "__main__":
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    http.server.ThreadingHTTPServer(("127.0.0.1", PORT), RangeHandler).serve_forever()
