"""External pricing policy service: refuse repricing deeper than 40 percent.

Set state/policy/mode.txt to healthy, slow, or overloaded to operate the service
under an explicit failure mode. Chio's adapter owns cache and timeout behavior.
"""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import hmac
import json
import os
import secrets
import time

directory = Path("state/policy")
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
token_path = directory / "token.txt"
if not token_path.exists():
    descriptor = os.open(token_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
    with os.fdopen(descriptor, "w") as target:
        target.write(secrets.token_hex(32))
token = token_path.read_text().strip()
mode_path = directory / "mode.txt"
if not mode_path.exists():
    mode_path.write_text("healthy")

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        if not hmac.compare_digest(self.headers.get("Authorization", ""), "Bearer " + token):
            self.send_error(401)
            return
        length = int(self.headers.get("Content-Length", 0))
        if self.path != "/evaluate" or not 0 < length <= 262144:
            self.send_error(400)
            return
        try:
            body = json.loads(self.rfile.read(length))
            percent = body["arguments"]["percent"]
            if not isinstance(percent, (int, float)):
                raise ValueError("percent must be a number")
            mode = mode_path.read_text().strip()
            if mode == "slow":
                time.sleep(1)
            elif mode == "overloaded":
                self.send_error(429, "Policy evaluation capacity is full")
                return
            elif mode != "healthy":
                self.send_error(503, "Policy configuration is unavailable")
                return
            decision = "deny" if percent > 40 else "allow"
            response = json.dumps({"decision": decision, "policy": "discount-ceiling-v1"}).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
        except (ValueError, KeyError):
            self.send_error(400)
        except BrokenPipeError:
            pass  # The caller's deadline elapsed; no tool execution is performed here.

print("Policy service: http://127.0.0.1:4314/evaluate", flush=True)
print("Credential: state/policy/token.txt; mode: state/policy/mode.txt", flush=True)
ThreadingHTTPServer(("127.0.0.1", 4314), Handler).serve_forever()
