#!/usr/bin/env python3
"""Send OpenAuditor's synthetic invoice using Python's standard library.

Set OPENAUDITOR_API_KEY, then run: python3 verify-invoice.py
Prints the full JSON response. HTTP 200 with verdict "false" is expected for
this example's missing PO reference; it is not a failed API request.
"""
import json
import os
import sys
import urllib.error
import urllib.request

EXAMPLE_URL = "https://openauditor.ai/examples/invoice.json"
VERIFY_URL = "https://openauditor.ai/api/v1/verify"


def main():
    key = os.environ.get("OPENAUDITOR_API_KEY", "").strip()
    if not key:
        print("Set OPENAUDITOR_API_KEY to a key from your OpenAuditor account.", file=sys.stderr)
        return 1
    try:
        with urllib.request.urlopen(EXAMPLE_URL, timeout=30) as source:
            body = source.read()
        json.loads(body)  # Check the downloaded request before submitting it.
        request = urllib.request.Request(
            VERIFY_URL,
            data=body,
            headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
            method="POST",
        )
        with urllib.request.urlopen(request, timeout=70) as response:
            result = json.load(response)
        print(json.dumps(result, indent=2))
        return 0
    except urllib.error.HTTPError as error:
        print(f"HTTP {error.code}; Request-Id: {error.headers.get('Request-Id', 'unavailable')}",
              file=sys.stderr)
        print(error.read().decode("utf-8", errors="replace"), file=sys.stderr)
    except (urllib.error.URLError, TimeoutError, ValueError) as error:
        print(f"Request could not be completed: {error}", file=sys.stderr)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
