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 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""
Billing + marketplace licensing API β€” docs/HARDENING.md Phase 4.

Two routers, both mounted by api/server.py:

    router          β€” /billing/*  license admin (org-scoped, T1 per
                      docs/TENANCY.md) + optional Stripe self-serve checkout
    experts_router  β€” /experts/{agent_id}/chat  license-key-gated delivery
                      proxy (metered per call)

Stripe is OPTIONAL by design. Without STRIPE_API_KEY the platform still
issues 'manual' licenses via POST /billing/licenses (design partners pay by
invoice) and all gating / metering / revocation behaves identically; the
Stripe endpoints (/billing/checkout, /billing/webhook) then 404 cleanly.
With STRIPE_API_KEY (+ STRIPE_WEBHOOK_SECRET for the webhook) Stripe adds
self-serve subscription checkout on top: checkout.session.completed issues
the license, customer.subscription.deleted revokes it.

Key handling (atp/licensing.py stores only the key_id half β€” never the
secret):
  * The plaintext licenseKey is returned exactly ONCE β€” in the POST
    /billing/licenses response. Save it then or re-issue.
  * Webhook-issued keys are DISCARDED here after issuance (the webhook
    response goes to Stripe, not the customer) β€” delivery happens
    out-of-band via the billing portal / support until a customer portal
    ships.
  * GET /billing/licenses never returns key material (keyId, the public
    identifier half, is not key material).

Enforcement model for /experts/{agent_id}/chat: the route is on the
auth-middleware allowlist (bearer optional) but the handler calls
atp.licensing.check_license on EVERY request β€” a DB status read per call is
the enforcement, there is deliberately NO cache of check results, so
revoking a license cuts this path off on the very next call.

Org scoping: /billing/* admin routes take the org ONLY from verified
request.state (set by the auth middleware from the JWT β€” TENANCY.md layer 1).
The expert gate authenticates by license key instead; the license ROW
carries the org its usage is metered under.
"""

from __future__ import annotations

import os
import re
import sys

from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel

from api.auth import require_role
from atp import licensing, store

router = APIRouter(prefix="/billing")
experts_router = APIRouter(prefix="/experts")

#: Backend spec for the expert delivery proxy (agents/backend.get_backend).
#: The dry-run default keeps the delivery path CI-exercisable with no keys.
EXPERT_SPEC_ENV = "ATP_EXPERT_SPEC"
EXPERT_SPEC_DEFAULT = "dryrun:candidate"


# ── Tenancy helper (same idiom as api/atp.py) ───────────────────────────────

def _org(request: Request) -> str:
    """Org for this request β€” ONLY from verified auth state (TENANCY.md Β§4
    layer 1). 'org-demo' when auth is disabled / legacy single-admin token."""
    return getattr(request.state, "org_id", None) or "org-demo"


# ── Seed catalog helpers (T0 β€” atp/store.get_data) ─────────────────────────

def _agent(agent_id: str) -> dict | None:
    for a in store.get_data().get("AGENTS", []):
        if a.get("id") == agent_id:
            return a
    return None


def _top_cert_label(agent: dict) -> str:
    """Label of the agent's highest-layer cert (Stripe product naming)."""
    certs = {c.get("id"): c for c in store.get_data().get("CERTS", [])}
    held = [certs[cid] for cid in (agent.get("certIds") or []) if cid in certs]
    if not held:
        return ""
    top = max(held, key=lambda c: c.get("layer") or 0)
    return str(top.get("label") or "")


def _unit_amount_usd(price: str | None) -> int | None:
    """Seed licensing.price ('$4,800/mo') β†’ Stripe unit_amount cents."""
    m = re.search(r"\$?\s*([0-9][0-9,]*(?:\.[0-9]+)?)", price or "")
    if not m:
        return None
    return int(round(float(m.group(1).replace(",", "")) * 100))


def _license_for_subscription(org_id: str,
                              subscription_id: str | None) -> dict | None:
    """The org's license bound to a Stripe subscription id, if any."""
    if not subscription_id:
        return None
    for row in licensing.list_licenses(org_id):
        if row.get("stripeSubscription") == subscription_id:
            return row
    return None


# ── Stripe (optional β€” endpoints 404 when unconfigured) ────────────────────

def _stripe_key() -> str | None:
    return os.environ.get("STRIPE_API_KEY") or None


def _stripe_configured_or_404():
    """Stripe endpoints don't exist without config β€” plain 404, no oracle."""
    if not _stripe_key():
        raise HTTPException(404, "Not Found")
    try:
        import stripe
    except ImportError as e:  # pragma: no cover β€” requirements.txt has it
        raise HTTPException(
            503, "stripe library not installed (pip install stripe)") from e
    stripe.api_key = _stripe_key()
    return stripe


def _cancel_subscription_best_effort(subscription_id: str | None) -> bool:
    """Cancel the Stripe subscription behind a revoked license. Best-effort
    by contract: the license is already revoked in OUR ledger (the expert
    gate is cut off regardless); a Stripe hiccup must not un-revoke it."""
    if not subscription_id or not _stripe_key():
        return False
    try:
        import stripe
        stripe.api_key = _stripe_key()
        stripe.Subscription.cancel(subscription_id)
        return True
    except Exception as e:  # noqa: BLE001 β€” best-effort by contract
        print(f"WARNING: stripe cancel of {subscription_id} failed: {e}",
              file=sys.stderr)
        return False


# ── License admin routes ────────────────────────────────────────────────────

class IssueBody(BaseModel):
    agentId: str
    kind: str = "production"   # licensing.VALID_KINDS
    expiresAt: str | None = None   # ISO-8601 UTC; None = perpetual


@router.post("/licenses", dependencies=[Depends(require_role("admin"))])
def billing_issue(body: IssueBody, request: Request):
    """Issue a 'manual' license for a marketplace agent (role admin).

    The Stripe-less path (design partners pay by invoice). Returns
    {license, licenseKey}; the plaintext licenseKey appears ONLY here β€”
    the engine stores just its key_id half.
    """
    try:
        return licensing.issue_license(_org(request), body.agentId, body.kind,
                                       expires_at=body.expiresAt)
    except licensing.UnknownAgentError as e:
        raise HTTPException(404, str(e)) from e
    except licensing.AgentNotLicensableError as e:
        raise HTTPException(400, str(e)) from e
    except ValueError as e:  # bad kind / expires_at
        raise HTTPException(400, str(e)) from e
    except licensing.LicenseSigningKeyError as e:
        raise HTTPException(503, str(e)) from e


@router.post("/licenses/{license_id}/reissue",
             dependencies=[Depends(require_role("admin"))])
def billing_reissue(license_id: str, request: Request):
    """Mint a fresh key for an active license (role admin). The previous key
    stops working immediately. This is how Stripe self-serve customers get
    their key: the webhook stores no plaintext, an org admin re-issues here
    and delivers it. Key shown ONCE."""
    try:
        return licensing.reissue_key(_org(request), license_id)
    except licensing.LicenseNotFoundError as e:
        raise HTTPException(404, str(e)) from e
    except ValueError as e:
        raise HTTPException(400, str(e)) from e
    except licensing.LicenseSigningKeyError as e:
        raise HTTPException(503, str(e)) from e


@router.get("/licenses",
            dependencies=[Depends(require_role("admin", "viewer"))])
def billing_licenses(request: Request):
    """Org's licenses, latest-first. Never contains key material β€” keys are
    shown once, at issue time (keyId is the public identifier half only)."""
    return {"licenses": licensing.list_licenses(_org(request))}


class RevokeBody(BaseModel):
    reason: str = ""


@router.post("/licenses/{license_id}/revoke",
             dependencies=[Depends(require_role("admin"))])
def billing_revoke(license_id: str, body: RevokeBody, request: Request):
    """Revoke a license (role admin, idempotent). Takes effect on the very
    next /experts call β€” the gate re-reads DB state every time. Cross-tenant
    ids 404 identically to unknown ids (TENANCY.md #6). When the license was
    Stripe-issued AND Stripe is configured, the subscription is cancelled
    too, best-effort."""
    try:
        revoked = licensing.revoke_license(
            _org(request), license_id, body.reason.strip() or "revoked by admin")
    except licensing.LicenseNotFoundError as e:
        raise HTTPException(404, f"license {license_id} not found") from e
    revoked["stripeCancelled"] = _cancel_subscription_best_effort(
        revoked.get("stripeSubscription"))
    return revoked


@router.get("/usage", dependencies=[Depends(require_role("admin", "viewer"))])
def billing_usage(request: Request, licenseId: str | None = None):
    """Metered usage for the org (optionally one license):
    {calls, tokensIn, tokensOut, byAgent}."""
    return licensing.usage_summary(_org(request), license_id=licenseId)


# ── Stripe self-serve checkout ──────────────────────────────────────────────

class CheckoutBody(BaseModel):
    agentId: str
    kind: str = "production"


@router.post("/checkout", dependencies=[Depends(require_role("admin"))])
def billing_checkout(body: CheckoutBody, request: Request):
    """Create a Stripe subscription Checkout Session for a seed listing.

    404 when STRIPE_API_KEY is unset (manual licensing still fully works).
    Price comes from the seed agent's licensing.price; the license itself is
    issued by the checkout.session.completed webhook, keyed by the metadata
    written here ({org_id, agent_id, kind} β€” org from verified state ONLY,
    so a tampered client cannot buy a license into another org).
    """
    stripe = _stripe_configured_or_404()
    org = _org(request)
    agent = _agent(body.agentId)
    if agent is None:
        raise HTTPException(404, f"agent {body.agentId} not found")
    if body.kind not in licensing.VALID_KINDS:
        raise HTTPException(
            400, f"kind must be one of {sorted(licensing.VALID_KINDS)}")
    seed_licensing = agent.get("licensing") or {}
    if not seed_licensing.get("available"):
        raise HTTPException(400, f"agent {body.agentId} is not licensable")
    unit_amount = _unit_amount_usd(seed_licensing.get("price"))
    if not unit_amount:
        raise HTTPException(
            400, f"agent {body.agentId} has no parseable price")

    label = _top_cert_label(agent)
    product_name = agent.get("name") or body.agentId
    if label:
        product_name = f"{product_name} β€” {label}"
    metadata = {"org_id": org, "agent_id": body.agentId, "kind": body.kind}
    base = (os.environ.get("BU_PUBLIC_URL")
            or request.headers.get("origin")
            or str(request.base_url)).rstrip("/")
    try:
        session = stripe.checkout.Session.create(
            mode="subscription",
            line_items=[{
                "quantity": 1,
                "price_data": {
                    "currency": "usd",
                    "unit_amount": unit_amount,
                    "recurring": {"interval": "month"},
                    "product_data": {"name": product_name},
                },
            }],
            # Session metadata drives checkout.session.completed issuance;
            # subscription_data.metadata puts the SAME keys on the
            # subscription object so customer.subscription.deleted can
            # resolve the org + license to revoke.
            metadata=metadata,
            subscription_data={"metadata": metadata},
            success_url=(base +
                         "/#/billing/success?session_id={CHECKOUT_SESSION_ID}"),
            cancel_url=base + "/#/billing/cancelled",
        )
    except Exception as e:  # noqa: BLE001 β€” stripe SDK error zoo
        raise HTTPException(502, f"stripe checkout failed: {e}") from e
    return {"url": session.url, "sessionId": session.id}


# ── Stripe webhook (public path β€” the signature IS the authentication) ─────

@router.post("/webhook")
async def billing_webhook(request: Request):
    """Stripe event sink. api/server.py adds this exact path to the auth
    allowlist: Stripe cannot send a bearer β€” every delivery is authenticated
    by its Stripe-Signature header, verified against STRIPE_WEBHOOK_SECRET
    (invalid/missing signature β†’ 400; Stripe unconfigured β†’ 404).

    Handled events (anything else is acknowledged and ignored):
      checkout.session.completed    β†’ issue the license from the session
        metadata ({org_id, agent_id, kind} written by /billing/checkout),
        storing the Stripe customer/subscription ids. Idempotent across
        Stripe's retries (one license per subscription). The plaintext key
        is DISCARDED here β€” only its key_id persists, so it is not
        retrievable later (out-of-band delivery via the billing portal).
      customer.subscription.deleted β†’ revoke the matching license
        (reason 'subscription cancelled').

    Responds 200 fast β€” handling is local DB writes only, no network calls.
    """
    if not _stripe_key() or not os.environ.get("STRIPE_WEBHOOK_SECRET"):
        raise HTTPException(404, "Not Found")
    import stripe

    payload = await request.body()
    sig_header = request.headers.get("stripe-signature", "")
    try:
        stripe.Webhook.construct_event(
            payload, sig_header, os.environ["STRIPE_WEBHOOK_SECRET"])
    except Exception as e:  # noqa: BLE001 β€” bad payload OR bad signature
        raise HTTPException(400, "invalid webhook signature") from e

    # construct_event verified signature + JSON; work on the verified bytes
    # as plain dicts (StripeObject's dict-likeness varies across versions).
    import json
    event = json.loads(payload)
    etype = event.get("type", "")
    obj = (event.get("data") or {}).get("object") or {}

    if etype == "checkout.session.completed":
        md = obj.get("metadata") or {}
        org, agent_id = md.get("org_id"), md.get("agent_id")
        kind = md.get("kind") or "production"
        if not (org and agent_id):
            return {"received": True, "handled": etype,
                    "skipped": "missing metadata"}
        subscription = obj.get("subscription")
        # Stripe retries deliveries β€” never double-issue for one sub.
        if subscription and _license_for_subscription(org, subscription):
            return {"received": True, "handled": etype,
                    "skipped": "already issued"}
        try:
            issued = licensing.issue_license(
                org, agent_id, kind,
                stripe_customer=obj.get("customer"),
                stripe_subscription=subscription)
        except (licensing.LicensingError, ValueError) as e:
            # Ack (200) so Stripe stops retrying a permanently-bad event,
            # but say what was wrong for the webhook log.
            print(f"WARNING: webhook license issue failed: {e}",
                  file=sys.stderr)
            return {"received": True, "handled": etype, "skipped": str(e)}
        # Hash-only persistence: the plaintext key never leaves this scope.
        return {"received": True, "handled": etype,
                "licenseId": issued["license"]["id"]}

    if etype == "customer.subscription.deleted":
        md = obj.get("metadata") or {}
        org, sub_id = md.get("org_id"), obj.get("id")
        if not (org and sub_id):
            return {"received": True, "handled": etype,
                    "skipped": "missing metadata"}
        row = _license_for_subscription(org, sub_id)
        if row is None:
            return {"received": True, "handled": etype,
                    "skipped": "no matching license"}
        licensing.revoke_license(org, row["id"], "subscription cancelled")
        return {"received": True, "handled": etype, "licenseId": row["id"]}

    return {"received": True, "ignored": etype}


# ── Expert delivery gate β€” /experts/{agent_id}/chat ─────────────────────────

class ChatBody(BaseModel):
    messages: list[dict]


def _persona(agent: dict) -> str:
    """Agent persona system prompt from T0 seed fields only (no tenant
    data β€” TENANCY.md leak surface #5)."""
    name = agent.get("name") or agent.get("id")
    level = agent.get("level")
    domains = ", ".join(agent.get("domains") or []) or "general"
    skills = ", ".join(
        s.get("name", "") for s in (agent.get("skills") or [])[:8])
    summary = (agent.get("reportCard") or {}).get("summary", "")
    boundaries = " ".join(
        f.get("boundary", "") for f in (agent.get("failures") or [])[:2])
    parts = [
        f"You are {name}, an ATP Level {level} certified expert agent "
        f"(domains: {domains}).",
        f"Certified skills: {skills}." if skills else "",
        summary,
        f"Known boundaries: {boundaries}" if boundaries else "",
        "Answer within your certified scope; when a request falls outside "
        "it, say so plainly and recommend human review.",
    ]
    return " ".join(p for p in parts if p)


def _flatten_messages(messages: list[dict]) -> str:
    """[{role, content}, ...] β†’ one transcript string (backends take a
    single system + user pair, agents/backend.Backend.complete)."""
    parts = []
    for m in messages:
        if not isinstance(m, dict):
            continue
        role = str(m.get("role", "user")).strip().lower() or "user"
        content = str(m.get("content", "")).strip()
        if content:
            parts.append(f"{role.capitalize()}: {content}")
    return "\n\n".join(parts)


def _license_org(license_key: str) -> str | None:
    """Org the checked license row belongs to.

    check_license()'s public license dict intentionally carries no org key
    (atp/store.py convention), but metering must land under the license
    ROW's org (T1) β€” never under a caller-supplied value, and the keyed
    machine caller has no bearer/org at all. Resolve it through the same
    key-id lookup check_license used; the in-package coupling to
    licensing's _parse_key/_load_by_key_id is deliberate β€” the alternative
    (raw licenses SQL here) would break the DAL-only convention
    (TENANCY.md layer 2).
    """
    parsed = licensing._parse_key(license_key)
    if not parsed:
        return None
    row = licensing._load_by_key_id(parsed[0])
    return (row or {}).get("org_id")


_DENIED_403 = ("revoked", "expired")


@experts_router.post("/{agent_id}/chat")
def expert_chat(
    agent_id: str,
    body: ChatBody,
    request: Request,
    license_key: str | None = Header(default=None, alias="X-ATP-License-Key"),
):
    """Licensed expert delivery (HARDENING.md Phase 4).

    Authentication is the LICENSE KEY (X-ATP-License-Key header), not a
    bearer β€” api/server.py puts '/experts/' on the middleware allowlist and
    THIS handler enforces instead: atp.licensing.check_license runs on EVERY
    request (a DB status read β€” deliberately uncached, so revocation cuts
    the path off on the very next call). 401 invalid key / 403 revoked or
    expired (with the reason). Every successful call appends a usage_events
    row (metering).
    """
    if not license_key or not license_key.strip():
        raise HTTPException(
            401, "missing license key (X-ATP-License-Key header)")
    license_key = license_key.strip()

    try:
        check = licensing.check_license(license_key)
    except licensing.LicenseSigningKeyError as e:
        raise HTTPException(503, str(e)) from e
    if not check.get("ok"):
        reason = str(check.get("reason") or "invalid")
        if reason in _DENIED_403:
            raise HTTPException(403, f"license {reason}")
        raise HTTPException(401, f"invalid license key ({reason})")
    lic = check.get("license") or {}

    if lic.get("agentId") != agent_id:
        raise HTTPException(
            403, f"license is for agent {lic.get('agentId')}, not {agent_id}")

    agent = _agent(agent_id)
    if agent is None:  # licensed against a since-removed seed agent
        raise HTTPException(404, f"agent {agent_id} not found")

    transcript = _flatten_messages(body.messages or [])
    if not transcript:
        raise HTTPException(400, "messages must contain at least one "
                                 "non-empty {role, content} entry")

    from agents.backend import get_backend
    spec = os.environ.get(EXPERT_SPEC_ENV, EXPERT_SPEC_DEFAULT)
    system = _persona(agent)
    try:
        reply = get_backend(spec).complete(system, transcript)
    except Exception as e:  # noqa: BLE001 β€” backend/network failures
        raise HTTPException(503, f"expert backend unavailable: {e}") from e

    # Metering β€” approx token counts (chars/4). No usage row, no reply:
    # usage_events is the append-only billing record (HARDENING.md Phase 4).
    org = _license_org(license_key) or "org-demo"
    try:
        usage = licensing.record_usage(
            org, lic.get("id"), agent_id,
            endpoint=f"/experts/{agent_id}/chat",
            tokens_in=max(1, (len(system) + len(transcript)) // 4),
            tokens_out=max(1, len(reply or "") // 4),
            status="ok",
        )
    except Exception as e:  # noqa: BLE001
        raise HTTPException(503, f"usage metering failed: {e}") from e

    return {"reply": reply, "usage": usage}