#!/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 /<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)
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)
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 http.server
import json
import os
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
SIGNUP_TOKEN_PATH = os.path.expanduser("~/carplay-signup-token.txt")
GOATLINK_TOKEN_PATH = os.path.expanduser("~/goatlink-signup-token.txt")


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": 4000,
        "temperature": 0.6,
    }
    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}


class Handler(http.server.SimpleHTTPRequestHandler):
    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 do_GET(self):
        parts = [p for p in self.path.split("?")[0].split("/") if p]
        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] == "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] == "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()
