"""Publish a metered result only after the Server accepts Usage."""
from pathlib import Path
from keygen_device_sdk import GatewayError, LicenseSDKError


def generate_report(client, amount: int = 1) -> None:
    staged = Path("staging/report.pdf")
    try:
        state = client.validate_or_raise()
        print("Current Usage:", state.uses, "/", state.max_uses)
        staged.parent.mkdir(parents=True, exist_ok=True)
        staged.write_bytes(b"example report")
        usage = client.increment_usage(amount)
        print(f"Publish {staged}; Usage accepted: {usage.uses}/{usage.max_uses}")
    except GatewayError as exc:
        staged.unlink(missing_ok=True)
        print(f"Usage rejected [{exc.code or exc.status_code}]: {exc}")
    except (LicenseSDKError, OSError, ValueError, TypeError) as exc:
        staged.unlink(missing_ok=True)
        print(f"Metered job failed: {exc}")
