#!/usr/bin/env python3
"""Waybill tracking API (lab build)."""
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

CONFIG = os.environ.get("WAYBILL_CONFIG", "./config/prod.json")

try:
    with open(CONFIG) as handle:
        config = json.load(handle)
except OSError as error:
    print(f"waybill: fatal: unable to open {CONFIG}: {error.strerror} (cwd={os.getcwd()})", flush=True)
    sys.exit(1)


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/healthz":
            self.send_error(404)
            return
        body = f"waybill: ready ({config['depot']})\n".encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("X-Waybill-Pid", str(os.getpid()))
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        print(f"waybill: {self.address_string()} {fmt % args}", flush=True)


address = (config["listen_host"], int(config["listen_port"]))
try:
    server = HTTPServer(address, Handler)
except OSError as error:
    print(f"waybill: fatal: cannot bind {address[0]}:{address[1]}: {error.strerror}", flush=True)
    sys.exit(1)
print(f"waybill: listening on http://{address[0]}:{address[1]} (depot {config['depot']})", flush=True)
server.serve_forever()
