#!/usr/bin/env python3
"""Waybill 2.6 (lab build): tracking API with a debug log and a /var space check."""
import os
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

CAPACITY = 100 * 1024 * 1024  # the /var volume
port = os.environ.get("WAYBILL_PORT")
if not port:
    hint = " (PORT is no longer read since 2.6; see CHANGELOG.md)" if os.environ.get("PORT") else ""
    print(f"waybill: fatal: WAYBILL_PORT is not set{hint}", file=sys.stderr, flush=True)
    sys.exit(78)
data = Path(os.environ.get("DATA_DIR", "var"))
debug = os.environ.get("LOG_LEVEL", "info") == "debug"


def used():
    return sum(p.stat().st_size for p in data.rglob("*") if p.is_file())


def debug_logger():
    log = data / "log/waybill/debug.log"
    chunk = ("DEBUG tracking lookup parcel=NW... cache=miss upstream=ledger latency_ms=12\n" * 2600).encode()
    while True:
        if used() < CAPACITY:
            with open(log, "ab") as out:
                out.write(chunk)
        time.sleep(1)


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def do_GET(self):
        if used() >= CAPACITY * 0.98:
            status, body = 507, "waybill: no space left on /var\n"
        else:
            status, body = 200, "waybill ok\n"
        data_out = body.encode()
        self.send_response(status)
        self.send_header("X-Waybill-Pid", str(os.getpid()))
        self.send_header("Content-Length", str(len(data_out)))
        self.end_headers()
        self.wfile.write(data_out)


if debug:
    print("waybill: LOG_LEVEL=debug, writing var/log/waybill/debug.log", file=sys.stderr, flush=True)
    threading.Thread(target=debug_logger, daemon=True).start()
print(f"waybill: listening on 127.0.0.1:{port}", file=sys.stderr, flush=True)
ThreadingHTTPServer(("127.0.0.1", int(port)), Handler).serve_forever()
