#!/usr/bin/env python3
"""ERP API v1 example. Python 3.9+; standard library only.

Set ERP_API_BASE (HTTPS URL ending /api/v1) and ERP_API_KEY on your server.
Optional ERP_STATE_DB defaults to erp-api-state.sqlite3 in the current directory.

    python erp-example.py account
    python erp-example.py submit order.json
    python erp-example.py poll ERPORD-0123456789
    python erp-example.py cancel ERPORD-0123456789 --items line-001 --operation-id cancel-001

This example never modifies a customer wallet. It saves result changes to a
SQLite outbox, which your ERP must consume with its own idempotent accounting
transaction. Do not send sample SKUs to the live service.
"""

import argparse
import hashlib
import json
import os
import re
import sqlite3
import sys
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class ApiError(RuntimeError):
    pass


class NoRedirect(HTTPRedirectHandler):
    """Do not forward an Authorization header to a redirected host."""
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def connect_state(filename):
    conn = sqlite3.connect(filename, timeout=15)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=FULL")
    conn.executescript("""
        CREATE TABLE IF NOT EXISTS submissions (
            external_order_id TEXT PRIMARY KEY,
            payload TEXT NOT NULL,
            idempotency_key TEXT NOT NULL UNIQUE,
            submission_id TEXT,
            last_response TEXT
        );
        CREATE TABLE IF NOT EXISTS task_results (
            task_id TEXT PRIMARY KEY,
            external_order_id TEXT NOT NULL,
            external_item_id TEXT NOT NULL,
            version INTEGER NOT NULL,
            result_id TEXT NOT NULL,
            status TEXT NOT NULL,
            billable_points INTEGER NOT NULL,
            refund_points INTEGER NOT NULL,
            snapshot TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS cancellations (
            operation_id TEXT PRIMARY KEY,
            submission_id TEXT NOT NULL,
            payload TEXT NOT NULL,
            idempotency_key TEXT NOT NULL UNIQUE,
            last_response TEXT
        );
        CREATE TABLE IF NOT EXISTS result_outbox (
            event_id TEXT PRIMARY KEY,
            task_id TEXT NOT NULL,
            result_id TEXT NOT NULL,
            external_order_id TEXT NOT NULL,
            external_item_id TEXT NOT NULL,
            billable_delta INTEGER NOT NULL,
            refund_delta INTEGER NOT NULL,
            snapshot TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            delivered_at TEXT,
            UNIQUE (task_id, result_id)
        );
    """)
    return conn


def configuration():
    base = os.environ.get("ERP_API_BASE", "").rstrip("/")
    key = os.environ.get("ERP_API_KEY", "")
    parts = urlsplit(base)
    if (parts.scheme != "https" or not parts.hostname or parts.username or
            parts.password or parts.query or parts.fragment or parts.path != "/api/v1"):
        raise ValueError("Set ERP_API_BASE to an HTTPS API URL ending /api/v1.")
    if not re.fullmatch(r"ERP_[A-Za-z0-9_-]{43}", key):
        raise ValueError("Set ERP_API_KEY to the key supplied by the administrator.")
    return urlunsplit(parts), key


def api_request(base, key, method, path, payload=None, idempotency_key=None):
    headers = {"Authorization": "Bearer " + key, "Accept": "application/json"}
    if payload is not None:
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    raw = payload.encode("utf-8") if payload is not None else None
    for attempt in range(3):
        request = Request(base + path, data=raw, headers=headers, method=method)
        try:
            with build_opener(NoRedirect).open(request, timeout=30) as response:
                return json.load(response)
        except HTTPError as exc:
            if exc.code >= 500 and attempt < 2:
                time.sleep(2 ** attempt)
                continue
            # Never print request headers or the API key.
            body = exc.read(8192).decode("utf-8", "replace")
            hint = " Wait at least 60 seconds before retrying." if exc.code == 429 else ""
            raise ApiError(f"HTTP {exc.code}: {body}{hint}") from None
        except (URLError, TimeoutError) as exc:
            if attempt < 2:
                time.sleep(2 ** attempt)
                continue
            raise ApiError("Request timed out or the connection failed. "
                           "Retry the same local order; its key is already saved.") from exc


def reserve_submission(conn, data):
    """Persist the business request BEFORE sending it; never regenerate on retry."""
    order_id = data.get("externalOrderId")
    if not isinstance(order_id, str) or not isinstance(data.get("items"), list):
        raise ValueError("order.json must contain externalOrderId and items.")
    # The server canonicalizes by externalItemId; use the same ordering locally.
    normalized = {"externalOrderId": order_id,
                  "items": sorted(data["items"], key=lambda item: item["externalItemId"])}
    payload = json.dumps(normalized, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute("SELECT * FROM submissions WHERE external_order_id=?", (order_id,)).fetchone()
        if row and row["payload"] != payload:
            raise ValueError("This externalOrderId is already saved with different content.")
        if not row:
            conn.execute("INSERT INTO submissions (external_order_id,payload,idempotency_key) VALUES (?,?,?)",
                         (order_id, payload, str(uuid.uuid4())))
            row = conn.execute("SELECT * FROM submissions WHERE external_order_id=?", (order_id,)).fetchone()
        conn.commit()
        return dict(row)
    except Exception:
        conn.rollback()
        raise


def reserve_cancellation(conn, submission_id, external_item_ids=None, operation_id=None):
    """Persist each cancel operation before sending; retry with its saved UUID.

    Omitting item IDs cancels accepted tasks in this order, not duplicate links.
    The default operation identity is derived from the order and canonical body;
    an ERP may supply its own stable local operation_id instead.
    """
    if not re.fullmatch(r"ERPORD-[A-F0-9]{10}", submission_id):
        raise ValueError("Invalid submission ID.")
    body = {}
    if external_item_ids is not None:
        if not isinstance(external_item_ids, list) or not 1 <= len(external_item_ids) <= 500:
            raise ValueError("externalItemIds must contain 1 to 500 IDs.")
        if any(not isinstance(item, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}", item)
               for item in external_item_ids):
            raise ValueError("Invalid external item ID.")
        if len(set(external_item_ids)) != len(external_item_ids):
            raise ValueError("Duplicate external item ID.")
        body["externalItemIds"] = sorted(external_item_ids)
    payload = json.dumps(body, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
    identity = operation_id or hashlib.sha256((submission_id + "\n" + payload).encode()).hexdigest()
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute("SELECT * FROM cancellations WHERE operation_id=?", (identity,)).fetchone()
        if row and (row["submission_id"] != submission_id or row["payload"] != payload):
            raise ValueError("This cancel operation is already saved with different content.")
        if not row:
            conn.execute("INSERT INTO cancellations (operation_id,submission_id,payload,idempotency_key) VALUES (?,?,?,?)",
                         (identity, submission_id, payload, str(uuid.uuid4())))
            row = conn.execute("SELECT * FROM cancellations WHERE operation_id=?", (identity,)).fetchone()
        conn.commit()
        return dict(row)
    except Exception:
        conn.rollback()
        raise


def cancel_submission(conn, base, key, submission_id, external_item_ids=None, operation_id=None):
    """Cancel with a durable UUID and persist versioned results for ERP accounting.

    CANCELLATION_NOT_ALLOWED means none of the requested new cancellations ran.
    Do not automatically replace UUIDs or widen the selection after an error.
    """
    saved = reserve_cancellation(conn, submission_id, external_item_ids, operation_id)
    response = api_request(base, key, "POST", "/submissions/" + submission_id + "/cancel",
                           saved["payload"], saved["idempotency_key"])
    changes = save_snapshot(conn, response)
    with conn:
        conn.execute("UPDATE cancellations SET last_response=? WHERE operation_id=?",
                     (json.dumps(response, ensure_ascii=False), saved["operation_id"]))
    return response, changes


def save_snapshot(conn, response):
    """Atomically save latest task versions AND their accounting outbox changes.

    refundPoints is a TARGET, not an event amount. failed->invalid has delta 0.
    pending->withdrawn releases a prior ERP precharge once (refund target 1).
    Old versions, duplicate submissions and expired detail are never re-credited.
    """
    submission = response["submission"]
    changes = []
    conn.execute("BEGIN IMMEDIATE")
    try:
        conn.execute("UPDATE submissions SET submission_id=?,last_response=? WHERE external_order_id=?",
                     (submission["id"], json.dumps(response, ensure_ascii=False), submission["externalOrderId"]))
        for item in submission.get("items", []):
            if item["status"] in ("duplicate", "expired"):
                continue
            task_id, result_id = item["taskId"], item["resultId"]
            prefix, separator, suffix = result_id.rpartition(":")
            if not separator or prefix != task_id or not suffix.isdecimal():
                raise ValueError("Unexpected resultId; stop and check the integration.")
            version = int(suffix)
            before = conn.execute("SELECT * FROM task_results WHERE task_id=?", (task_id,)).fetchone()
            if before and version <= before["version"]:
                continue
            billable, refund = int(item["billablePoints"]), int(item["refundPoints"])
            billable_delta = billable - (before["billable_points"] if before else 0)
            refund_delta = refund - (before["refund_points"] if before else 0)
            snapshot = json.dumps(item, ensure_ascii=False)
            conn.execute("""INSERT INTO task_results
                (task_id,external_order_id,external_item_id,version,result_id,status,billable_points,refund_points,snapshot)
                VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET
                version=excluded.version,result_id=excluded.result_id,status=excluded.status,
                billable_points=excluded.billable_points,refund_points=excluded.refund_points,snapshot=excluded.snapshot""",
                         (task_id, submission["externalOrderId"], item["externalItemId"], version,
                          result_id, item["status"], billable, refund, snapshot))
            if not billable_delta and not refund_delta:
                continue
            event_id = "erp-result:" + result_id
            conn.execute("""INSERT INTO result_outbox
                (event_id,task_id,result_id,external_order_id,external_item_id,billable_delta,refund_delta,snapshot)
                VALUES (?,?,?,?,?,?,?,?)""",
                         (event_id, task_id, result_id, submission["externalOrderId"], item["externalItemId"],
                          billable_delta, refund_delta, snapshot))
            changes.append({"eventId": event_id, "externalOrderId": submission["externalOrderId"],
                            "externalItemId": item["externalItemId"], "billableDelta": billable_delta,
                            "refundDelta": refund_delta})
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    return changes


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True)
    commands.add_parser("account")
    commands.add_parser("submit").add_argument("file", type=Path)
    commands.add_parser("poll").add_argument("submission_id")
    cancellation = commands.add_parser("cancel")
    cancellation.add_argument("submission_id")
    cancellation.add_argument("--items", nargs="+", help="externalItemIds; omit to cancel all accepted tasks in this order")
    cancellation.add_argument("--operation-id", help="Your stable local cancel operation ID, reused on retries")
    args = parser.parse_args()
    base, key = configuration()
    if args.command == "account":
        print(json.dumps(api_request(base, key, "GET", "/account"), ensure_ascii=False, indent=2))
        return
    with connect_state(os.environ.get("ERP_STATE_DB", "erp-api-state.sqlite3")) as conn:
        if args.command == "submit":
            data = json.loads(args.file.read_text(encoding="utf-8-sig"))
            saved = reserve_submission(conn, data)
            response = api_request(base, key, "POST", "/submissions", saved["payload"], saved["idempotency_key"])
        elif args.command == "cancel":
            response, changes = cancel_submission(conn, base, key, args.submission_id, args.items, args.operation_id)
            print(json.dumps({"response": response, "savedAccountingChanges": changes}, ensure_ascii=False, indent=2))
            return
        else:
            if not re.fullmatch(r"ERPORD-[A-F0-9]{10}", args.submission_id):
                raise ValueError("Invalid submission ID.")
            response = api_request(base, key, "GET", "/submissions/" + args.submission_id)
        changes = save_snapshot(conn, response)
        print(json.dumps({"response": response, "savedAccountingChanges": changes}, ensure_ascii=False, indent=2))


# ERP wallet consumer pseudocode (must be implemented inside YOUR accounting DB):
# BEGIN;
#   INSERT processed_event(event_id) ...;  -- UNIQUE(event_id); duplicate => no-op
#   lookup customer by (externalOrderId, externalItemId), verify original charge;
#   apply the saved target-minus-old target correction using YOUR billing rules;
#   record wallet entry and event_id in this same transaction;
# COMMIT;
# Then mark result_outbox.delivered_at. A crash before this marker is safe because
# processed_event is unique. Do not expose this example's API key to the browser.

if __name__ == "__main__":
    try:
        main()
    except (ApiError, ValueError, KeyError, OSError, sqlite3.Error) as exc:
        print(str(exc), file=sys.stderr)
        sys.exit(1)
