"""One explicitly authorized provider confirmation example with caller-supplied content.""" from __future__ import annotations import json import os import urllib.error from datetime import UTC, datetime, timedelta from pathlib import Path from scheduling_core.ledger import Ledger, OperationState from scheduling_core.postmark import BoundMessage, PostmarkAdapter, PostmarkHttpsClient TRANSACTION_ID = "public-sample-confirmation-test-v1" OPERATION_KEY = "public-sample-confirmation-test-send-v1" def main() -> int: if os.environ.get("SCHEDULING_AUTHORIZED_SUPERVISED_TEST") != "1": print("FAIL one-shot authorization gate is not enabled") return 1 token = os.environ.get("POSTMARK_SERVER_TOKEN", "") sender = os.environ.get("SCHEDULING_TEST_SENDER", "") recipient = os.environ.get("SCHEDULING_TEST_RECIPIENT", "") subject = os.environ.get("SCHEDULING_TEST_SUBJECT", "") body = os.environ.get("SCHEDULING_TEST_MESSAGE_BODY", "") database = os.environ.get("SCHEDULING_TEST_DATABASE", "") if not all((token, sender, recipient, subject, body, database)): print("FAIL token, test sender, recipient, subject, message body, and database configuration are required") return 1 ledger = Ledger(Path(database)) ledger.create_authorized_owner_delivery_test( transaction_id=TRANSACTION_ID, sender=sender, recipient=recipient, expires_at=datetime.now(UTC) + timedelta(minutes=15), ) existing = ledger.operation_for_key(OPERATION_KEY) if existing is not None and existing["state"] in {OperationState.PENDING, OperationState.UNCERTAIN}: print(f"NO_SEND state={existing['state']} reconciliation_required") return 2 client = PostmarkHttpsClient(secret_provider=lambda: token, enabled=True) try: message_id = PostmarkAdapter(ledger, client).send_bound_message( TRANSACTION_ID, OPERATION_KEY, sender, recipient, BoundMessage(subject, body), ) except urllib.error.HTTPError as error: print(f"FAIL provider HTTP {error.code}") return 1 except Exception: operation = ledger.operation_for_key(OPERATION_KEY) print(f"NO_SEND state={operation['state'] if operation else 'unknown'} reconciliation_required") return 2 operation = ledger.operation_for_key(OPERATION_KEY) if message_id is None or operation is None or operation["state"] != OperationState.ACCEPTED: print("NO_SEND state=uncertain reconciliation_required") return 2 print(json.dumps({"message_id": message_id, "accepted_at": operation["updated_at"], "status": "accepted"}, sort_keys=True)) return 0 if __name__ == "__main__": raise SystemExit(main())