#!/usr/bin/env python3
"""CarPlay relay: serves ~/carplay-feed-relay on port 22027, accepts unit
event POSTs, and proxies the truck Rex brain to NVIDIA NIM.

GET  /<token>/feed.json            -> the book's feed payload (read-only)
GET  /<token>/version.json         -> update-channel manifest
GET  /<token>/muse-carplay.apk     -> the current APK for in-app updates
POST /<token>/events               -> appends one JSON event per line to
                                      ~/carplay-feed-relay-inbox/events.jsonl
POST /<token>/rex                  -> Rex brain: {text, feed} in,
                                      {say, action} out (NVIDIA NIM)
GET  /<token>/rex/health           -> {ok, model, cap used/limit}
POST /<signup-token>/signup        -> website snow-signup intake: appends
                                      one JSON signup per line to
                                      ~/carplay-feed-relay-inbox/signups.jsonl
                                      (token in ~/carplay-signup-token.txt,
                                      signup-only: grants no other route)
POST /<signup-token>/garden-booking -> Garden Goats customer booking-page
                                      intake: appends one JSON booking per
                                      line to ~/carplay-feed-relay-inbox/
                                      garden-bookings.jsonl (same website
                                      token; validated name/phone/address,
                                      service from the rate-card list, window
                                      Morning/Afternoon; a booking is a
                                      REQUEST — GoatLink sync turns it into
                                      an open opportunity for the provider
                                      to confirm; nothing is auto-booked)
GET  /<signup-token>/garden-bookings -> the parsed garden-bookings.jsonl
                                      array (read-only; GoatLink sync pulls)
POST /<goatlink-token>/goatlink-signup -> GoatLink Connect customer signup
                                      intake: appends one JSON signup per
                                      line to ~/carplay-feed-relay-inbox/
                                      goatlink-signups.jsonl
                                      (token in ~/goatlink-signup-token.txt,
                                      signup-only: grants no other route)
GET  /<goatlink-token>/goatlink-signups -> the parsed goatlink-signups.jsonl
                                      array (read-only; GoatLink sync pulls)
POST /<goatlink-token>/goatlink-stripe-event -> appends one Stripe status
                                      event per line to goatlink-stripe-
                                      events.jsonl (written by the VM sync
                                      script, applied by GoatLink). Events
                                      carry a tenantId, or a checkout email
                                      + plan pair matched by the sync script
                                      against the signup inbox.
GET  /<goatlink-token>/goatlink-stripe-events -> the parsed events array
POST /<goatlink-token>/goatlink-stripe-webhook -> Stripe webhook receiver
                                      (signature-verified with the endpoint
                                      secret in ~/.goatlink-webhook/secret,
                                      mode 600; verified events are mapped to
                                      the same goatlink-stripe-status records
                                      the polling sync posts and appended to
                                      goatlink-stripe-events.jsonl; a bad
                                      signature gets a 400 and records
                                      nothing)
GET  /<token>/morning.json         -> CarPlay fallback morning package:
                                      {generatedAt, feedUpdatedAt, feed} --
                                      the current feed payload wrapped with a
                                      generation stamp, for the app to cache
                                      at day start (token-gated like
                                      feed.json)
POST /<token>/studio               -> Prototype Studio design assist:
                                      {idea, context} in, {brief, model} out
                                      (NVIDIA NIM reasoning model; called
                                      server-side by the studio app only)
Header-auth inbox reads (G2, 2026-11-25): GET /inbox/goatlink-signups,
/inbox/goatlink-stripe-events, /inbox/goatlink-stripe-webhooks and
/inbox/goatlink-job-leads with 'Authorization: Bearer <goatlink token>';
GET /inbox/garden-bookings with 'Authorization: Bearer <signup token>'.
A missing or wrong token gets a 404, same as the legacy routes.
Everything else: 404. The token directory name is the only credential
for the unit-facing routes; the NVIDIA key lives server-side in
~/.rex-brain/key.env (mode 600) and never leaves this box."""
import hashlib
import hmac
import http.server
import json
import os
import time
import urllib.request
from datetime import datetime
from zoneinfo import ZoneInfo

ROOT = os.path.expanduser("~/carplay-feed-relay")
INBOX = os.path.expanduser("~/carplay-feed-relay-inbox")
BRAIN_DIR = os.path.expanduser("~/.rex-brain")
PORT = 22027
MAX_EVENT_BYTES = 64 * 1024
MAX_REX_BYTES = 128 * 1024
MAX_SIGNUP_BYTES = 16 * 1024
BOOKING_SERVICES = ("Fall cleanup", "Snow removal (per visit)",
                    "Snow season contract", "Gutter cleaning",
                    "Lawn care", "Other property work")
BOOKING_WINDOWS = ("Morning", "Afternoon")
SIGNUP_TOKEN_PATH = os.path.expanduser("~/carplay-signup-token.txt")
GOATLINK_TOKEN_PATH = os.path.expanduser("~/goatlink-signup-token.txt")
STRIPE_WEBHOOK_SECRET_PATH = os.path.expanduser("~/.goatlink-webhook/secret")
STRIPE_SUB_MAP_PATH = os.path.join(INBOX, "goatlink-stripe-sub-map.json")
MAX_WEBHOOK_BYTES = 256 * 1024
# Live Stripe price id -> GoatLink plan name (same table the VM polling
# sync uses; only the four self-serve prices attribute a payment).
PRICE_TO_PLAN = {
    "price_1UfRSeQc6gNuJJjCTPcH9DEO": "Growth",
    "price_1UfSiCQc6gNuJJjCyhaVD8WM": "Growth",
    "price_1UfRSfQc6gNuJJjCTAs7ocRk": "Pro",
    "price_1UfSiDQc6gNuJJjCpQbgpCKi": "Pro",
}
# Stripe subscription status -> GoatLink status (same map as the polling
# sync). Stripe statuses absent here record nothing.
STRIPE_STATUS_MAP = {"active": "active", "trialing": "active",
                     "past_due": "past_due", "unpaid": "past_due",
                     "canceled": "cancelled",
                     "incomplete_expired": "cancelled"}


def load_signup_token():
    try:
        with open(SIGNUP_TOKEN_PATH) as fh:
            return fh.read().strip() or None
    except OSError:
        return None


def load_goatlink_token():
    try:
        with open(GOATLINK_TOKEN_PATH) as fh:
            return fh.read().strip() or None
    except OSError:
        return None

NIM_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
NIM_MODEL = "nvidia/nemotron-3.5-lightning-30b-a3b"
DAILY_CAP = 300  # Rex requests per America/Chicago day
CT = ZoneInfo("America/Chicago")

SYSTEM_PROMPT = """You are Rex, the assistant in Charlie's work truck (Garden Goats LLC, St. Paul MN). Charlie speaks to you while driving or working. Answer in ONE or TWO short sentences meant to be spoken aloud. No lists, no markdown.

You are given today's feed as JSON context: the route stops (name, address, service, done), money (collected, to check), and the sunset time. Snow rates if asked: $575 per season, $65 to $70 per visit, salt included. Never invent a stop, price, time, or person that is not in the context. If the answer is not in the context, say you don't have it.

You may request ONE action per reply by setting "action":
- {"type": "mark_done", "address": "<exact address from the route>"} when Charlie says a stop is done or finished.
- {"type": "navigate", "address": "<exact address from the route>"} when Charlie asks for directions to a stop.
- {"type": "dial", "name": "Jack Jerguson"}, {"type": "dial", "name": "Rachael Bell"}, or {"type": "dial", "name": "JB"} when Charlie asks to call one of them.
- {"type": "none"} otherwise.

Respond with ONLY a JSON object: {"say": "<what to speak>", "action": {"type": "none"}}"""


STUDIO_MODEL = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"
STUDIO_DAILY_CAP = 100  # studio requests per America/Chicago day
STUDIO_DIR = os.path.expanduser("~/.studio-brain")
MAX_STUDIO_BYTES = 32 * 1024

STUDIO_PROMPT = """You are the design assistant inside Prototype Studio, Charlie's DIY build-planning workshop (Garden Goats LLC, St. Paul MN). Charlie describes a build idea; you develop it into a build brief a fabricator can act on.

Studio rules — follow them exactly:
- EVERY dimension or load figure you state carries one tag: [MEASURED] (ONLY for a figure Charlie himself stated in his idea or context — never tag your own numbers MEASURED), [SOURCED] (a typical published figure — name the kind of source), [VERIFY] (he must measure his own equipment before cutting), [DESIGN TARGET] (a goal to design to, never a certified rating), or [ESTIMATE] (your computed approximation — show the basis in a few words).
- Never present an invented specification as fact. Anything you don't know goes in the VERIFY list, not in the design as a number.
- No prices, no brand recommendations stated as fact, no safety certifications. Where a load matters, design to the worst credible case and say so.
- Assume a home shop: MIG welder, angle grinder, drill, flat work surface. No tube roller, no CNC, no lathe unless he says otherwise.

Answer with these sections, in order, in plain text with the section names as headers:
CONCEPT — what it is and the problem it solves, 2-3 sentences.
HOW IT WORKS — the mechanism and the load path, where the forces go.
MAIN PARTS — the pieces, each with material form (tube, plate, angle) and tagged key dimensions.
KEY CHECKS — the 2-4 structural or fit checks that decide whether this design is sound.
BUILD ORDER — a short numbered sketch of the assembly sequence.
VERIFY BEFORE CUTTING — the list of measurements he must take on his own equipment first.
RISKS — failure modes and what in the design answers each one.

Keep it tight and concrete — mechanics over adjectives. If the idea is underspecified, make the reasonable assumption, tag it, and keep moving; end the brief with the single question whose answer would most change the design."""


def studio_usage_today():
    path = os.path.join(STUDIO_DIR, "usage.json")
    today = datetime.now(CT).strftime("%Y-%m-%d")
    try:
        with open(path) as fh:
            data = json.load(fh)
        if data.get("date") == today:
            return data
    except Exception:
        pass
    return {"date": today, "count": 0, "prompt_tokens": 0,
            "completion_tokens": 0}


def studio_reply(idea, context):
    key = load_nim_key()
    if not key:
        return 503, {"error": "brain key not configured on the relay"}
    usage = studio_usage_today()
    if usage["count"] >= STUDIO_DAILY_CAP:
        return 429, {"error": "daily studio cap reached",
                     "cap": STUDIO_DAILY_CAP}
    user = "Build idea: " + idea
    if context:
        user += "\n\nWorkshop context from Charlie: " + context
    payload = {
        "model": STUDIO_MODEL,
        "messages": [
            {"role": "system", "content": STUDIO_PROMPT},
            {"role": "user", "content": user},
        ],
        "max_tokens": 1500,
        "temperature": 0.6,
        # Nemotron reasoning model: with thinking on it burned the whole
        # 4000-token budget on hidden reasoning and returned no content
        # (verified live 2026-11-26); thinking off lands a complete brief
        # in ~625 tokens. Same pattern as rex_reply.
        "chat_template_kwargs": {"enable_thinking": False},
    }
    req = urllib.request.Request(
        NIM_URL,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": "Bearer " + key,
                 "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            out = json.load(resp)
    except Exception as exc:
        return 502, {"error": "studio upstream failed: " + type(exc).__name__}
    u = out.get("usage") or {}
    usage["count"] += 1
    usage["prompt_tokens"] += u.get("prompt_tokens") or 0
    usage["completion_tokens"] += u.get("completion_tokens") or 0
    os.makedirs(STUDIO_DIR, exist_ok=True)
    path = os.path.join(STUDIO_DIR, "usage.json")
    tmp = path + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(usage, fh)
    os.replace(tmp, path)
    brief = ((out.get("choices") or [{}])[0].get("message") or {}).get(
        "content") or ""
    brief = brief.strip()
    if not brief:
        return 502, {"error": "studio model returned no content"}
    return 200, {"brief": brief, "model": STUDIO_MODEL}


def load_nim_key():
    try:
        with open(os.path.join(BRAIN_DIR, "key.env")) as fh:
            for line in fh:
                if line.startswith("NVIDIA_NIM_API_KEY="):
                    return line.strip().split("=", 1)[1]
    except OSError:
        pass
    return None


def usage_today():
    path = os.path.join(BRAIN_DIR, "usage.json")
    today = datetime.now(CT).strftime("%Y-%m-%d")
    try:
        with open(path) as fh:
            data = json.load(fh)
        if data.get("date") == today:
            return data
    except Exception:
        pass
    return {"date": today, "count": 0, "prompt_tokens": 0,
            "completion_tokens": 0}


def usage_record(usage, prompt_tokens, completion_tokens):
    usage["count"] += 1
    usage["prompt_tokens"] += prompt_tokens or 0
    usage["completion_tokens"] += completion_tokens or 0
    path = os.path.join(BRAIN_DIR, "usage.json")
    tmp = path + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(usage, fh)
    os.replace(tmp, path)


def rex_reply(text, feed):
    key = load_nim_key()
    if not key:
        return 503, {"error": "brain key not configured on the relay"}
    usage = usage_today()
    if usage["count"] >= DAILY_CAP:
        return 429, {"error": "daily Rex cap reached", "cap": DAILY_CAP}
    context = "No feed context supplied."
    if isinstance(feed, dict):
        context = "Today's feed JSON:\n" + json.dumps(feed)[:6000]
    payload = {
        "model": NIM_MODEL,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": context + "\n\nCharlie says: " + text},
        ],
        "max_tokens": 300,
        "temperature": 0.3,
        # Nemotron is a reasoning model: without this it burns the whole
        # token budget thinking and returns no content (verified live).
        "chat_template_kwargs": {"enable_thinking": False},
    }
    req = urllib.request.Request(
        NIM_URL,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": "Bearer " + key,
                 "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=45) as resp:
            out = json.load(resp)
    except Exception as exc:
        return 502, {"error": "brain upstream failed: " + type(exc).__name__}
    u = out.get("usage") or {}
    usage_record(usage, u.get("prompt_tokens"), u.get("completion_tokens"))
    raw = ((out.get("choices") or [{}])[0].get("message") or {}).get(
        "content") or ""
    raw = raw.strip()
    if raw.startswith("```"):
        raw = raw.strip("`")
        if raw.startswith("json"):
            raw = raw[4:]
        raw = raw.strip()
    try:
        parsed = json.loads(raw)
        say = str(parsed.get("say") or "").strip()
        action = parsed.get("action") or {"type": "none"}
        if not isinstance(action, dict) or "type" not in action:
            action = {"type": "none"}
    except Exception:
        say, action = raw, {"type": "none"}
    if not say:
        say = "I didn't catch that."
    return 200, {"say": say, "action": action, "model": NIM_MODEL}


def load_stripe_webhook_secret():
    try:
        with open(STRIPE_WEBHOOK_SECRET_PATH) as fh:
            return fh.read().strip() or None
    except OSError:
        return None


def verify_stripe_signature(raw, header, secret):
    """Stripe v1 signature: HMAC-SHA256 of '<t>.<raw body>' keyed with the
    endpoint secret; any matching v1 value passes; 5-minute tolerance."""
    if not header or not secret:
        return False
    ts = None
    sigs = []
    for part in header.split(","):
        if "=" not in part:
            continue
        k, v = part.split("=", 1)
        if k.strip() == "t":
            ts = v.strip()
        elif k.strip() == "v1":
            sigs.append(v.strip())
    if not ts or not sigs:
        return False
    try:
        if abs(time.time() - int(ts)) > 300:
            return False
    except ValueError:
        return False
    signed = ts.encode("utf-8") + b"." + raw
    expected = hmac.new(secret.encode("utf-8"), signed,
                        hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in sigs)


def _sub_map():
    try:
        with open(STRIPE_SUB_MAP_PATH) as fh:
            data = json.load(fh)
        if isinstance(data, dict):
            return data
    except Exception:
        pass
    return {}


def _sub_map_remember(sub_id, tenant, email, plan):
    if not sub_id:
        return
    data = _sub_map()
    entry = data.get(sub_id) or {}
    for key, val in (("tenantId", tenant), ("email", email),
                     ("plan", plan)):
        if val:
            entry[key] = val
    data[sub_id] = entry
    os.makedirs(INBOX, exist_ok=True)
    tmp = STRIPE_SUB_MAP_PATH + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(data, fh)
    os.replace(tmp, STRIPE_SUB_MAP_PATH)


def _plan_from_items(items):
    for item in items or []:
        price_id = ((item.get("price") or {}).get("id")) or ""
        if price_id in PRICE_TO_PLAN:
            return PRICE_TO_PLAN[price_id]
    return ""


def stripe_webhook_record(event):
    """Map one verified Stripe event to a goatlink-stripe-status inbox
    record (the shape the polling sync posts), or None to record
    nothing. Attribution is exact: a tenant id, or an email the app can
    match to a signup -- never a guess."""
    etype = event.get("type") or ""
    obj = ((event.get("data") or {}).get("object")) or {}
    tenant = ""
    email = ""
    plan = ""
    sub_id = ""
    status = None
    stripe_status = ""
    if etype == "checkout.session.completed":
        if obj.get("mode") != "subscription":
            return None
        tenant = str(obj.get("client_reference_id") or "").strip()
        details = obj.get("customer_details") or {}
        email = str(details.get("email") or
                    obj.get("customer_email") or "").strip().lower()
        sub_id = str(obj.get("subscription") or "")
        if obj.get("payment_status") not in ("paid",
                                             "no_payment_required"):
            return None
        status = "active"
        stripe_status = "checkout.session.completed"
    elif etype in ("customer.subscription.updated",
                   "customer.subscription.deleted"):
        sub_id = str(obj.get("id") or "")
        meta = obj.get("metadata") or {}
        tenant = str(meta.get("tenantId") or
                     meta.get("client_reference_id") or "").strip()
        plan = _plan_from_items(((obj.get("items") or {}).get("data")))
        raw_status = "canceled" if etype.endswith("deleted") else \
            str(obj.get("status") or "")
        status = STRIPE_STATUS_MAP.get(raw_status)
        stripe_status = raw_status
        if not status:
            return None
    elif etype == "invoice.payment_failed":
        sub_id = str(obj.get("subscription") or "")
        email = str(obj.get("customer_email") or "").strip().lower()
        plan = _plan_from_items(((obj.get("lines") or {}).get("data")))
        status = "past_due"
        stripe_status = "invoice.payment_failed"
    else:
        return None
    if sub_id and (tenant or email or plan):
        _sub_map_remember(sub_id, tenant, email, plan)
    if not tenant and not email and sub_id:
        known = _sub_map().get(sub_id) or {}
        tenant = str(known.get("tenantId") or "")
        email = str(known.get("email") or "")
        if not plan:
            plan = str(known.get("plan") or "")
    if not tenant and not email:
        return None
    return {"type": "goatlink-stripe-status", "tenantId": tenant,
            "status": status, "email": email, "plan": plan,
            "subscription": sub_id, "stripeStatus": stripe_status,
            "receivedAt": datetime.now(CT).isoformat()}


class Handler(http.server.SimpleHTTPRequestHandler):
    # HTTP/1.1 keep-alive (G2, 2026-11-25): every response this server
    # sends carries Content-Length (_json, send_error, file serving),
    # so persistent connections frame correctly. Under HTTP/1.0 the
    # close-after-response behaviour raced keep-alive clients (GoatLink
    # sync) into intermittent ECONNRESETs on pooled sockets.
    protocol_version = "HTTP/1.1"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=ROOT, **kwargs)

    def end_headers(self):
        if self.path.split("?")[0].endswith("feed.json"):
            try:
                rel = self.path.split("?")[0].lstrip("/")
                mtime = int(os.path.getmtime(os.path.join(ROOT, rel)))
                self.send_header("X-Feed-Updated", str(mtime))
            except OSError:
                pass
            self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def _json(self, code, obj):
        body = json.dumps(obj).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _token_ok(self, parts):
        return len(parts) >= 2 and os.path.isdir(
            os.path.join(ROOT, parts[0]))

    def _bearer_token(self):
        auth = self.headers.get("Authorization", "")
        if auth.startswith("Bearer "):
            return auth[7:].strip() or None
        return None

    def _inbox_records(self, fname):
        records = []
        try:
            with open(os.path.join(INBOX, fname)) as fh:
                for line in fh:
                    line = line.strip()
                    if line:
                        records.append(json.loads(line))
        except OSError:
            records = []
        return records

    def do_GET(self):
        parts = [p for p in self.path.split("?")[0].split("/") if p]
        # G2 header-auth inbox routes (2026-11-25): the relay inbox token
        # travels in the Authorization: Bearer header, never in the URL.
        # Legacy token-in-path GET routes below stay for backward compat.
        if len(parts) == 2 and parts[0] == "inbox":
            name = parts[1]
            goatlink_files = {
                "goatlink-signups": "goatlink-signups.jsonl",
                "goatlink-stripe-events": "goatlink-stripe-events.jsonl",
                "goatlink-stripe-webhooks": "goatlink-stripe-events.jsonl",
                "goatlink-job-leads": "goatlink-job-leads.jsonl",
            }
            if name == "garden-bookings":
                expected = load_signup_token()
                fname = "garden-bookings.jsonl"
            elif name in goatlink_files:
                expected = load_goatlink_token()
                fname = goatlink_files[name]
            else:
                self.send_error(404)
                return
            provided = self._bearer_token()
            if not expected or not provided or not hmac.compare_digest(
                    provided, expected):
                self.send_error(404)
                return
            self._json(200, {"records": self._inbox_records(fname)})
            return
        if len(parts) == 2 and parts[1] == "garden-bookings":
            token = load_signup_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            records = []
            try:
                with open(os.path.join(INBOX, "garden-bookings.jsonl")) as fh:
                    for line in fh:
                        line = line.strip()
                        if line:
                            records.append(json.loads(line))
            except OSError:
                records = []
            self._json(200, {"records": records})
            return
        if len(parts) == 2 and parts[1] in ("goatlink-signups",
                                            "goatlink-stripe-events"):
            token = load_goatlink_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            fname = ("goatlink-signups.jsonl" if parts[1] ==
                     "goatlink-signups" else "goatlink-stripe-events.jsonl")
            records = []
            try:
                with open(os.path.join(INBOX, fname)) as fh:
                    for line in fh:
                        line = line.strip()
                        if line:
                            records.append(json.loads(line))
            except OSError:
                records = []
            self._json(200, {"records": records})
            return
        if len(parts) == 2 and parts[1] == "goatlink-stripe-webhooks":
            token = load_goatlink_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            records = []
            try:
                with open(os.path.join(INBOX, "goatlink-stripe-events.jsonl")) as fh:
                    for line in fh:
                        line = line.strip()
                        if line:
                            records.append(json.loads(line))
            except OSError:
                records = []
            self._json(200, {"records": records})
            return
        if len(parts) == 2 and parts[1] == "morning.json" \
                and self._token_ok(parts):
            feed_path = os.path.join(ROOT, parts[0], "feed.json")
            try:
                with open(feed_path) as fh:
                    feed = json.load(fh)
                updated = int(os.path.getmtime(feed_path))
            except Exception:
                self._json(503, {"error": "feed unavailable"})
                return
            self._json(200, {
                "generatedAt": datetime.now(CT).isoformat(),
                "feedUpdatedAt": updated,
                "feed": feed,
            })
            return
        if len(parts) == 3 and parts[1] == "rex" and parts[2] == "health" \
                and self._token_ok(parts):
            usage = usage_today()
            self._json(200, {"ok": True, "model": NIM_MODEL,
                             "cap": {"used": usage["count"],
                                     "limit": DAILY_CAP,
                                     "date": usage["date"]}})
            return
        super().do_GET()

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.send_header("Content-Length", "0")
        self.end_headers()

    def do_POST(self):
        parts = [p for p in self.path.split("?")[0].split("/") if p]
        if len(parts) == 2 and parts[1] == "goatlink-stripe-webhook":
            token = load_goatlink_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            secret = load_stripe_webhook_secret()
            if not secret:
                self._json(503, {"error": "webhook secret not configured"})
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_WEBHOOK_BYTES:
                self._json(400, {"error": "bad webhook size"})
                return
            raw = self.rfile.read(length)
            if not verify_stripe_signature(
                    raw, self.headers.get("Stripe-Signature"), secret):
                self._json(400, {"error": "signature verification failed"})
                return
            try:
                event = json.loads(raw.decode("utf-8"))
                if not isinstance(event, dict):
                    raise ValueError("event must be a JSON object")
            except Exception:
                self._json(400, {"error": "bad webhook json"})
                return
            record = stripe_webhook_record(event)
            if record:
                os.makedirs(INBOX, exist_ok=True)
                with open(os.path.join(
                        INBOX, "goatlink-stripe-events.jsonl"), "a") as fh:
                    fh.write(json.dumps(record) + "\n")
            self._json(200, {"received": True,
                             "recorded": bool(record)})
            return
        if len(parts) == 2 and parts[1] == "garden-booking":
            token = load_signup_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_SIGNUP_BYTES:
                self.send_error(400, "bad booking size")
                return
            try:
                booking = json.loads(self.rfile.read(length).decode("utf-8"))
                if not isinstance(booking, dict):
                    raise ValueError("booking must be a JSON object")
                name = str(booking.get("name") or "").strip()[:160]
                phone = str(booking.get("phone") or "").strip()[:60]
                address = str(booking.get("address") or "").strip()[:300]
                service = str(booking.get("service") or "").strip()
                date = str(booking.get("date") or "").strip()[:40]
                window = str(booking.get("window") or "").strip()
                email = str(booking.get("email") or "").strip()[:160]
                details = str(booking.get("details") or "").strip()[:2000]
                hold = booking.get("hold") is True
                multi = booking.get("multiProperty") is True
                prop_count = str(booking.get("propertyCount") or ""
                                 ).strip()[:10]
                prop_notes = str(booking.get("propertyNotes") or ""
                                 ).strip()[:4000]
                if not name or not phone or not address:
                    raise ValueError("name, phone, address required")
                if service not in BOOKING_SERVICES:
                    raise ValueError("unknown service")
                if window not in BOOKING_WINDOWS:
                    raise ValueError("window must be Morning or Afternoon")
            except Exception:
                self.send_error(400, "bad booking json")
                return
            record = {"type": "garden-booking", "name": name,
                      "phone": phone, "address": address,
                      "service": service, "date": date, "window": window,
                      "email": email, "details": details,
                      "hold": hold, "multiProperty": multi,
                      "propertyCount": prop_count,
                      "propertyNotes": prop_notes,
                      "receivedAt": datetime.now(CT).isoformat()}
            os.makedirs(INBOX, exist_ok=True)
            with open(os.path.join(INBOX, "garden-bookings.jsonl"),
                      "a") as fh:
                fh.write(json.dumps(record) + "\n")
            body = b'{"ok":true}'
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if len(parts) == 2 and parts[1] == "signup":
            token = load_signup_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_SIGNUP_BYTES:
                self.send_error(400, "bad signup size")
                return
            try:
                signup = json.loads(self.rfile.read(length).decode("utf-8"))
                if not isinstance(signup, dict):
                    raise ValueError("signup must be a JSON object")
                name = str(signup.get("name") or "").strip()
                phone = str(signup.get("phone") or "").strip()
                address = str(signup.get("address") or "").strip()
                plan = str(signup.get("plan") or "").strip()
                if not name or not phone or not address:
                    raise ValueError("name, phone, address required")
            except Exception:
                self.send_error(400, "bad signup json")
                return
            record = {"type": "snow-signup", "name": name, "phone": phone,
                      "address": address, "plan": plan,
                      "receivedAt": datetime.now(CT).isoformat()}
            os.makedirs(INBOX, exist_ok=True)
            with open(os.path.join(INBOX, "signups.jsonl"), "a") as fh:
                fh.write(json.dumps(record) + "\n")
            body = b'{"ok":true}'
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if len(parts) == 2 and parts[1] == "goatlink-signup":
            token = load_goatlink_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_SIGNUP_BYTES:
                self.send_error(400, "bad signup size")
                return
            try:
                signup = json.loads(self.rfile.read(length).decode("utf-8"))
                if not isinstance(signup, dict):
                    raise ValueError("signup must be a JSON object")
                business = str(signup.get("business") or "").strip()
                contact = str(signup.get("contact") or "").strip()
                email = str(signup.get("email") or "").strip()
                phone = str(signup.get("phone") or "").strip()
                plan = str(signup.get("plan") or "").strip()
                if not business or not email or "@" not in email:
                    raise ValueError("business and a valid email required")
                if plan not in ("Free", "Growth", "Pro", "Enterprise"):
                    raise ValueError("unknown plan")
            except Exception:
                self.send_error(400, "bad signup json")
                return
            record = {"type": "goatlink-signup", "business": business,
                      "contact": contact, "email": email, "phone": phone,
                      "plan": plan,
                      "receivedAt": datetime.now(CT).isoformat()}
            os.makedirs(INBOX, exist_ok=True)
            with open(os.path.join(INBOX, "goatlink-signups.jsonl"),
                      "a") as fh:
                fh.write(json.dumps(record) + "\n")
            body = b'{"ok":true}'
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if len(parts) == 2 and parts[1] == "goatlink-stripe-event":
            token = load_goatlink_token()
            if not token or parts[0] != token:
                self.send_error(404)
                return
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_SIGNUP_BYTES:
                self.send_error(400, "bad event size")
                return
            try:
                event = json.loads(self.rfile.read(length).decode("utf-8"))
                if not isinstance(event, dict):
                    raise ValueError("event must be a JSON object")
                tenant = str(event.get("tenantId") or "").strip()
                status = str(event.get("status") or "").strip()
                email = str(event.get("email") or "").strip().lower()
                plan = str(event.get("plan") or "").strip()
                attributed = bool(tenant) or (bool(email) and
                                              plan in ("Growth", "Pro"))
                if not attributed or status not in ("active", "past_due",
                                                    "cancelled"):
                    raise ValueError("tenantId or email+plan, and a known status, required")
            except Exception:
                self.send_error(400, "bad event json")
                return
            record = {"type": "goatlink-stripe-status",
                      "tenantId": tenant, "status": status,
                      "email": email, "plan": plan,
                      "subscription": str(event.get("subscription") or ""),
                      "stripeStatus": str(event.get("stripeStatus") or ""),
                      "receivedAt": datetime.now(CT).isoformat()}
            os.makedirs(INBOX, exist_ok=True)
            with open(os.path.join(INBOX, "goatlink-stripe-events.jsonl"),
                      "a") as fh:
                fh.write(json.dumps(record) + "\n")
            body = b'{"ok":true}'
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if len(parts) == 2 and parts[1] == "rex" and self._token_ok(parts):
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_REX_BYTES:
                self._json(400, {"error": "bad request size"})
                return
            try:
                body = json.loads(self.rfile.read(length).decode("utf-8"))
                text = str(body.get("text") or "").strip()
                if not text:
                    raise ValueError("text required")
            except Exception:
                self._json(400, {"error": "bad request json"})
                return
            code, obj = rex_reply(text, body.get("feed"))
            self._json(code, obj)
            return
        if len(parts) == 2 and parts[1] == "studio" \
                and self._token_ok(parts):
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_STUDIO_BYTES:
                self._json(400, {"error": "bad request size"})
                return
            try:
                body = json.loads(self.rfile.read(length).decode("utf-8"))
                idea = str(body.get("idea") or "").strip()
                if not idea:
                    raise ValueError("idea required")
                context = str(body.get("context") or "").strip()
            except Exception:
                self._json(400, {"error": "bad request json"})
                return
            code, obj = studio_reply(idea, context)
            self._json(code, obj)
            return
        if len(parts) == 2 and parts[1] == "events" \
                and self._token_ok(parts):
            try:
                length = int(self.headers.get("Content-Length", "0"))
            except ValueError:
                length = 0
            if length <= 0 or length > MAX_EVENT_BYTES:
                self.send_error(400, "bad event size")
                return
            raw = self.rfile.read(length)
            try:
                event = json.loads(raw.decode("utf-8"))
                if not isinstance(event, dict) or "type" not in event:
                    raise ValueError("event must be a JSON object with a type")
            except Exception:
                self.send_error(400, "bad event json")
                return
            os.makedirs(INBOX, exist_ok=True)
            with open(os.path.join(INBOX, "events.jsonl"), "a") as fh:
                fh.write(json.dumps(event) + "\n")
            body = b'{"ok":true}'
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        self.send_error(404)

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    http.server.ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
