#!/usr/bin/env python3
"""Minimal ContentDividend URVP reference verifier.

Run:
    python reference_server.py

POST JSON to http://127.0.0.1:8787/verify-status

{
  "receipt_id": "cdurvpr_...",
  "resource": "https://publisher.example/article",
  "requested_use": "rag"
}

The reference server calls the public ContentDividend receipt-status endpoint.
It never stores a buyer token and never creates rights.
"""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import urlopen
from urllib.parse import quote
import json
import os

BASE=os.environ.get("CONTENTDIVIDEND_BASE_URL","https://app.contentdividend.com").rstrip("/")

class Handler(BaseHTTPRequestHandler):
    def _send(self,status,payload):
        raw=json.dumps(payload,separators=(",",":")).encode()
        self.send_response(status)
        self.send_header("Content-Type","application/json")
        self.send_header("Cache-Control","no-store")
        self.send_header("Content-Length",str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)

    def do_POST(self):
        if self.path!="/verify-status":
            return self._send(404,{"error":"not_found"})
        try:
            length=int(self.headers.get("Content-Length","0"))
            body=json.loads(self.rfile.read(length) or b"{}")
            rid=str(body.get("receipt_id") or "")
            resource=str(body.get("resource") or "")
            requested_use=str(body.get("requested_use") or "")
            if not rid or not resource or not requested_use:
                return self._send(400,{"error":"receipt_id, resource and requested_use are required"})
            with urlopen(BASE+"/v1/public/rights-receipts/"+quote(rid,safe="")+"/status",timeout=10) as r:
                status=json.loads(r.read().decode())
            allowed=bool(
                status.get("currently_authorized") is True and
                status.get("resource")==resource and
                status.get("requested_use")==requested_use
            )
            return self._send(200,{
                "allow":allowed,
                "receipt_id":rid,
                "resource":resource,
                "requested_use":requested_use,
                "contentdividend_status":status,
                "reference_server_grants_rights":False
            })
        except Exception as exc:
            return self._send(502,{"allow":False,"error":"verification_failed","detail":str(exc)})

if __name__=="__main__":
    host=os.environ.get("HOST","127.0.0.1")
    port=int(os.environ.get("PORT","8787"))
    print(f"URVP reference verifier listening on http://{host}:{port}")
    ThreadingHTTPServer((host,port),Handler).serve_forever()
