#!/usr/bin/env python3
"""UpDash Mail API: the sandbox flow end to end, standard library only (Python 3.9+).

    XM_API=https://<mail api host> XM_KEY=xm_test_... python3 sandbox.py

Optional: XM_DEALER (dealer id or your external dealer id; default: your first dealer),
XM_WEBHOOK_PUBLIC_URL (a public https URL that forwards to this script's receiver, e.g. a tunnel;
without it the receiver listens on 127.0.0.1, which only a local Mail API can reach) and
XM_WEBHOOK_PORT (the receiver's port on 127.0.0.1, for the tunnel to forward to; default: any free port).
Sandbox keys (xm_test_) never print or mail anything.
"""

import atexit
import hashlib
import hmac
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer

API = os.environ.get("XM_API", "").rstrip("/")
# The most the person you work for said to spend, in cents: never the quote total alone.
BUDGET_CENTS = int(os.environ.get("XM_MAX_SPEND_CENTS", "50000"))
KEY = os.environ.get("XM_KEY", "")
APPROVAL_WAIT_SECONDS = int(os.environ.get("XM_APPROVAL_WAIT_SECONDS") or 900)
if not API or not KEY.startswith("xm_test_"):
    print("Set XM_API (the Mail API base URL) and XM_KEY (a sandbox key, xm_test_...).", file=sys.stderr)
    sys.exit(2)


def step(title):
    print(f"\n== {title}", flush=True)


def fail(message, detail=None):
    print(f"FAILED: {message}", file=sys.stderr)
    if detail is not None:
        print(json.dumps(detail, indent=2)[:2000], file=sys.stderr)
    sys.exit(1)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


OPENER = urllib.request.build_opener(NoRedirect)


def request(method, url, body=None, headers=None):
    """Send a request; returns (status, headers, text). HTTP errors are returned, not raised."""
    req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
    try:
        with OPENER.open(req, timeout=60) as res:
            return res.status, res.headers, res.read().decode("utf-8")
    except urllib.error.HTTPError as e:
        return e.code, e.headers, e.read().decode("utf-8")


def api(method, path, body=None, headers=None):
    """Call the API with the key. Errors carry {"error": {"code", "message", "fix"}}."""
    h = {"authorization": f"Bearer {KEY}", **(headers or {})}
    data = None
    if body is not None:
        h["content-type"] = "application/json"
        data = json.dumps(body).encode("utf-8")
    status, _, text = request(method, f"{API}{path}", data, h)
    try:
        return status, json.loads(text) if text else None
    except ValueError:
        return status, {"raw": text[:200]}


def expect(result, status, what):
    got, body = result
    if got != status:
        fail(f"{what}: expected HTTP {status}, got {got}", body)
    return body


def verify_signature(secret, header, raw_body, tolerance_seconds=300):
    """X-Xcel-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>" keyed with the secret>."""
    try:
        parts = dict(p.split("=", 1) for p in (header or "").split(","))
        t = int(parts["t"])
    except (ValueError, KeyError):
        return False
    if abs(time.time() - t) > tolerance_seconds:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))


# A tiny webhook receiver: keeps the raw body (the signature covers the exact bytes) and answers 200.
received = []


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("content-length", "0")))
        received.append({"signature": self.headers.get("x-xcel-signature"), "type": self.headers.get("x-xcel-event-type"), "body": body})
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok")

    def log_message(self, *args):
        pass


server = HTTPServer(("127.0.0.1", int(os.environ.get("XM_WEBHOOK_PORT") or 0)), Receiver)
threading.Thread(target=server.serve_forever, daemon=True).start()
print(f"webhook receiver on http://127.0.0.1:{server.server_address[1]}")
hook_url = os.environ.get("XM_WEBHOOK_PUBLIC_URL") or f"http://127.0.0.1:{server.server_address[1]}/xm-hook"

step("Products and dealer")
products = expect(api("GET", "/v1/products"), 200, "list products")["products"]
product = next((p for p in products if p["code"] == "postcard_6x9"), products[0])
print(f"{len(products)} products; using {product['code']}")
dealers = expect(api("GET", "/v1/dealers"), 200, "list dealers")["dealers"]
dealer = os.environ.get("XM_DEALER") or (dealers[0].get("external_id") or dealers[0]["id"] if dealers else None)
if not dealer:
    fail("No dealer: ask Xcel to add one to your partner account.")

step("Webhook endpoint")
status, hook = api("POST", "/v1/webhooks", {"url": hook_url})
secret = hook["secret"] if status == 201 else None
hook_id = hook["id"] if status == 201 else None
print(f"registered {hook_url}" if secret else f"not registered ({(hook or {}).get('error', {}).get('code')}): signatures will not be checked")


def deactivate_hook():
    """Deactivate the endpoint this run registered, also after fail() (its pending deliveries are cancelled)."""
    d_status, _ = api("DELETE", f"/v1/webhooks/{hook_id}")
    print("webhook endpoint deactivated" if d_status == 200 else f"could not deactivate the webhook endpoint (HTTP {d_status})")


if hook_id:
    atexit.register(deactivate_hook)

step("Campaign")
name = f"Example {datetime.now(timezone.utc).isoformat()}"
campaign = expect(api("POST", "/v1/campaigns", {"dealer_id": dealer, "product_code": product["code"], "name": name}), 201, "create campaign")["campaign"]
cid = campaign["id"]
print(f"campaign {cid} ({campaign['status']})")

step("Audience: signed upload URL, PUT the CSV, complete")
upload = expect(api("POST", f"/v1/campaigns/{cid}/audience", {}), 201, "start upload")
# external_id is your own record id: per-lead results come back keyed by it. Never an email or phone.
csv = "\r\n".join(
    [
        "external_id,first_name,last_name,address1,city,state,zip,vehicle_year,vehicle_make,vehicle_model",
        "cust-2001,Taylor,Sample,100 Main St,Springfield,IL,62701,2021,Ford,F-150",
        "cust-2002,Jordan,Example,2200 Oak Ave,Columbus,OH,43215,2019,Toyota,Camry",
        "cust-2003,Sam,Placeholder,35 Elm Rd,Austin,TX,78701,2022,Honda,CR-V",
    ]
)
put_status, _, _ = request("PUT", upload["upload_url"], csv.encode("utf-8"), {"content-type": "text/csv"})
if put_status != 200:
    fail(f"PUT the CSV: HTTP {put_status}")
completed = expect(api("POST", f"/v1/campaigns/{cid}/audience/complete", {"audience_id": upload["audience_id"]}), 200, "complete upload")
print(f"mailable {completed['audience']['mailable_count']} of {completed['audience']['submitted_count']}")

step("Creative")
template = "postcard_6x9_birthday"
# The gift is a dealer fact, so it goes in copy. With AI copy configured, a brief writes the note;
# otherwise write the copy yourself.
gift = {"gift_offer": "$50 toward any service", "expires": "12/31/2026"}
status, creative = api(
    "POST",
    f"/v1/campaigns/{cid}/creative",
    {
        "template_code": template,
        "brief": {"goal": "Wish customers a happy birthday this month and invite them in for their gift", "offer": "$50 toward any service, good through 12/31/2026", "tone": "warm"},
        "copy": gift,
    },
)
if status == 201 and creative["creative"]["preflight"]["ok"]:
    print(f"brief: AI copy {creative['ai_copy']['status']}")
else:
    print(f"brief not used ({(creative or {}).get('error', {}).get('code', 'preflight issues')}): sending copy")
    copy = {
        **gift,
        "note": "Happy birthday from all of us! Thank you for trusting us with your {{recipient.vehicle|vehicle}}. Your gift is on the other side: stop by any time this month.",
    }
    status, creative = api("POST", f"/v1/campaigns/{cid}/creative", {"template_code": template, "copy": copy})
gen = expect((status, creative), 201, "generate creative")
if not gen["creative"]["preflight"]["ok"]:
    fail("preflight", gen["creative"]["preflight"]["issues"])
print(f"creative v{gen['creative']['version']}, preflight ok")

step("Proof, quote, approval")
proof = expect(api("POST", f"/v1/campaigns/{cid}/proof"), 200, "render proof")
print(f"proof: {len(proof['pages'])} pages, PDF {'rendered' if proof['renderer']['pdf_available'] else 'not available here'}")
quote = expect(api("POST", f"/v1/campaigns/{cid}/quote", {}), 201, "get quote")["quote"]
print(f"quote: {quote['quantity']} pieces, {quote['total_cents']} cents")
approval = expect(api("POST", f"/v1/campaigns/{cid}/approval", {"quote_id": quote["id"], "max_spend_cents": BUDGET_CENTS}), 201, "request approval")
# Only a person approves spend, so this script stops and asks one. The sandbox returns the link so
# you can play the approver; a live link goes by email to the dealer's approver and never to you.
# XM_SANDBOX_APPROVE=1 decides through the sandbox test route instead, for CI. A live key is refused there.
if os.environ.get("XM_SANDBOX_APPROVE") == "1":
    expect(api("POST", f"/v1/test/campaigns/{cid}/approval", {"approval_id": approval["approval_id"], "decision": "approve"}), 200, "approve through the sandbox route")
    print("approved through the sandbox route")
else:
    print(f"\nA person decides here. Open this link, check the proof and approve the order:\nreview_url: {approval['review_url']}\nWaiting up to {APPROVAL_WAIT_SECONDS} seconds...", flush=True)
    deadline = time.time() + APPROVAL_WAIT_SECONDS
    while True:
        state = expect(api("GET", f"/v1/campaigns/{cid}"), 200, "read the approval")
        decided = (state.get("latest_approval") or {}).get("status")
        if decided == "approved":
            break
        if decided == "rejected":
            fail("the approver rejected the order: change it, render a proof and request approval again.")
        if time.time() > deadline:
            fail(f"nobody decided within {APPROVAL_WAIT_SECONDS} seconds. Set XM_APPROVAL_WAIT_SECONDS to wait longer.")
        time.sleep(3)
    print("approved on the review page")

step("Submit (Idempotency-Key) and advance")
idem = str(uuid.uuid4())
submitted = expect(api("POST", f"/v1/campaigns/{cid}/submit", {"approval_id": approval["approval_id"]}, {"idempotency-key": idem}), 201, "submit")
_, replay = api("POST", f"/v1/campaigns/{cid}/submit", {"approval_id": approval["approval_id"]}, {"idempotency-key": idem})
if (replay or {}).get("submission_id") != submitted["submission_id"]:
    fail("a retry with the same Idempotency-Key must replay the first response", replay)
print(f"submitted {submitted['submission_id']}; the retry replayed it")
while True:
    status, adv = api("POST", f"/v1/test/campaigns/{cid}/advance", {})
    if status != 200:
        break
    print(f"-> {adv['status']} ({adv['status_label']})")
    if adv["status"] == "completed":
        break

step("Results, page by page")
after = None
leads = 0
for page in range(1, 51):
    query = {"leads_limit": "2", **({"leads_after": after} if after else {})}
    r = expect(api("GET", f"/v1/campaigns/{cid}/results?{urllib.parse.urlencode(query)}"), 200, "get results")
    if page == 1:
        print(f"results: {json.dumps((r.get('results') or {}).get('responses'))} ({'simulated' if (r.get('results') or {}).get('simulated') else 'live'})")
    for lead in r["leads"]["items"]:
        leads += 1
        amounts = ", ".join(f"{m['kind']} {m['revenue_cents']} cents" for m in lead["matches"])
        print(f"  {lead['external_id'] or '(no id)'}: {', '.join(x['type_label'] or str(x['type']) for x in lead['responses'])}{'; ' + amounts if amounts else ''}")
    after = r["leads"]["next_after"]
    if not after:
        break
if leads == 0:
    fail("expected simulated per-lead results after completing the sandbox order")

step("Webhooks")
if secret:
    deadline = time.time() + 15
    while time.time() < deadline and not any(r["type"] == "campaign.status_changed" for r in received):
        time.sleep(0.25)
    if not received:
        fail("no webhook arrived within 15 seconds")
    bad = [r for r in received if not verify_signature(secret, r["signature"], r["body"])]
    if bad:
        fail(f"{len(bad)} webhook(s) failed signature verification")
    print(f"{len(received)} webhook(s), every signature verified: {', '.join(sorted({r['type'] for r in received}))}")
else:
    print("skipped: no webhook endpoint (see XM_WEBHOOK_PUBLIC_URL)")

server.shutdown()
print("\nDone: the sandbox order ran end to end.")
