import json, re, time
biz = str(input.get("business") or "").strip()[:80] or "a small business"
visitor = re.sub(r"[^a-z0-9-]", "", str(input.get("visitor") or "").lower())[:40] or "anon"
reply = str(input.get("reply") or "")
spec = None
m = re.search(r"\{.*\}", reply, re.S)
if m:
    try:
        spec = json.loads(m.group(0))
    except Exception:
        spec = None
spec = spec if isinstance(spec, dict) else {}

BANNED = re.compile(r"prompt|system|instruction|pipeline|database|table|model|openai|gpt|token|api", re.I)

def clean_text(v, cap):
    s = re.sub(r"[<>{}`]", "", str(v or "")).strip()[:cap]
    return "" if BANNED.search(s) else s

def word(v, fallback, cap=16):
    w = re.sub(r"[^a-z-]", "", str(v or "").lower())[:cap]
    return w or fallback

refuse = spec.get("refuse")
if refuse is not None:
    note = clean_text(refuse, 140) or ("Name a real business — a dental clinic, a surf shop, "
                                       "a law firm — and I will build for it.")
    output = {"rows": [], "refused": note}
else:
    kind = str(input.get("kind") or "").strip().lower()
    KINDS = ("intake", "pipeline", "booking", "inventory", "approvals",
             "tasks", "waitlist", "feedback", "quote", "loyalty")
    if kind not in KINDS:
        kind = "intake"
    source = "model"
    title = clean_text(spec.get("title"), 40)
    meta = {}

    if kind == "pipeline":
        stages = [clean_text(s, 12) for s in (spec.get("stages") or []) if clean_text(s, 12)][:4]
        samples = []
        for s in (spec.get("samples") or []):
            if isinstance(s, dict) and clean_text(s.get("name"), 24):
                samples.append({"name": clean_text(s.get("name"), 24),
                                "detail": clean_text(s.get("detail"), 24)})
            if len(samples) >= 3:
                break
        if len(stages) < 3:
            source = "fallback"
            stages = ["New", "In progress", "Done"]
        if not samples:
            samples = [{"name": "First one", "detail": "example"}]
        meta = {"card_noun": word(spec.get("card_noun"), "card"), "stages": stages, "samples": samples}
        title = title or ("Pipeline — " + biz[:26])
    elif kind == "booking":
        days = [clean_text(d, 10) for d in (spec.get("days") or []) if clean_text(d, 10)][:3]
        times = [clean_text(t, 8) for t in (spec.get("times") or []) if clean_text(t, 8)][:4]
        if len(days) < 2 or len(times) < 2:
            source = "fallback"
            days = days if len(days) >= 2 else ["Mon", "Tue", "Wed"]
            times = times if len(times) >= 2 else ["9:00", "11:00", "2:00"]
        meta = {"slot_noun": word(spec.get("slot_noun"), "booking"), "days": days, "times": times}
        title = title or ("Bookings — " + biz[:26])
    elif kind == "inventory":
        items = []
        for it in (spec.get("items") or []):
            if not isinstance(it, dict) or not clean_text(it.get("name"), 20):
                continue
            try:
                qty = max(0, min(99, int(it.get("qty"))))
            except Exception:
                qty = 5
            items.append({"name": clean_text(it.get("name"), 20), "qty": qty,
                          "unit": clean_text(it.get("unit"), 10) or "units"})
            if len(items) >= 5:
                break
        if len(items) < 3:
            source = "fallback"
            items = [{"name": "Item A", "qty": 8, "unit": "units"},
                     {"name": "Item B", "qty": 3, "unit": "units"},
                     {"name": "Item C", "qty": 12, "unit": "units"}]
        meta = {"items": items}
        title = title or ("Stock — " + biz[:28])
    elif kind == "approvals":
        reqs = []
        for r in (spec.get("requests") or []):
            if isinstance(r, dict) and clean_text(r.get("title"), 26):
                reqs.append({"title": clean_text(r.get("title"), 26),
                             "detail": clean_text(r.get("detail"), 30)})
            if len(reqs) >= 4:
                break
        if len(reqs) < 2:
            source = "fallback"
            reqs = [{"title": "First request", "detail": "awaiting review"},
                    {"title": "Second request", "detail": "awaiting review"}]
        meta = {"request_noun": word(spec.get("request_noun"), "request"), "requests": reqs}
        title = title or ("Approvals — " + biz[:24])
    elif kind == "tasks":
        tasks = []
        for t in (spec.get("tasks") or []):
            name = clean_text(t.get("title") if isinstance(t, dict) else t, 28)
            if name:
                tasks.append({"title": name})
            if len(tasks) >= 6:
                break
        if len(tasks) < 3:
            source = "fallback"
            tasks = [{"title": "Open up"}, {"title": "Restock"}, {"title": "Close out the day"}]
        meta = {"task_noun": word(spec.get("task_noun"), "task"), "tasks": tasks}
        title = title or ("Checklist — " + biz[:24])
    elif kind == "waitlist":
        samples = [clean_text(s, 18) for s in (spec.get("samples") or []) if clean_text(s, 18)][:3]
        if not samples:
            samples = ["First guest"]
        meta = {"party_noun": word(spec.get("party_noun"), "guest"), "samples": samples}
        title = title or ("Waitlist — " + biz[:25])
    elif kind == "feedback":
        q = clean_text(spec.get("question"), 40) or "How was your visit?"
        meta = {"question": q, "thanks": clean_text(spec.get("thanks"), 30) or "Thank you."}
        title = title or ("Feedback — " + biz[:25])
    elif kind == "quote":
        items = []
        for it in (spec.get("items") or []):
            if not isinstance(it, dict) or not clean_text(it.get("name"), 22):
                continue
            try:
                price = max(1, min(9999, int(it.get("price"))))
            except Exception:
                price = 100
            items.append({"name": clean_text(it.get("name"), 22), "price": price})
            if len(items) >= 5:
                break
        if len(items) < 3:
            source = "fallback"
            items = [{"name": "Base service", "price": 200},
                     {"name": "Add-on", "price": 80},
                     {"name": "Rush", "price": 50}]
        cur = str(spec.get("currency") or "$").strip()[:2] or "$"
        meta = {"currency": cur, "items": items}
        title = title or ("Quote — " + biz[:27])
    elif kind == "loyalty":
        members = []
        for mm in (spec.get("members") or []):
            if isinstance(mm, dict) and clean_text(mm.get("name"), 18):
                try:
                    pts = max(0, min(400, int(mm.get("points"))))
                except Exception:
                    pts = 0
                members.append({"name": clean_text(mm.get("name"), 18), "points": pts})
            if len(members) >= 3:
                break
        if not members:
            members = [{"name": "First member", "points": 20}]
        try:
            reward_at = max(50, min(500, int(spec.get("reward_at"))))
        except Exception:
            reward_at = 100
        meta = {"member_noun": word(spec.get("member_noun"), "member"),
                "reward_at": reward_at, "members": members}
        title = title or ("Loyalty — " + biz[:25])
    else:
        TYPES = {"text", "select", "date", "phone", "email"}
        KEY_RE = re.compile(r"[^a-z0-9_]")
        fields = []
        for f in (spec.get("fields") or []):
            if not isinstance(f, dict):
                continue
            key = KEY_RE.sub("", str(f.get("key") or "").lower())[:24]
            label = clean_text(f.get("label"), 24)
            ftype = str(f.get("type") or "text").lower()
            if not key or not label or ftype not in TYPES:
                continue
            fd = {"key": key, "label": label, "type": ftype}
            if ftype == "select":
                opts = [clean_text(o, 28) for o in (f.get("options") or []) if clean_text(o, 28)][:4]
                if len(opts) < 2:
                    fd["type"] = "text"
                else:
                    fd["options"] = opts
            fields.append(fd)
            if len(fields) >= 5:
                break
        if len(fields) < 3:
            source = "fallback"
            fields = [{"key": "name", "label": "Name", "type": "text"},
                      {"key": "contact", "label": "Phone or email", "type": "text"},
                      {"key": "reason", "label": "Reason for visit", "type": "text"},
                      {"key": "date", "label": "Preferred date", "type": "date"}]
        meta = {"noun": word(spec.get("record_noun"), "record"),
                "fields": fields, "placeholder": clean_text(spec.get("placeholder"), 40)}
        title = title or ("Intake — " + biz[:28])

    d = spec.get("design") if isinstance(spec.get("design"), dict) else {}
    accent = str(d.get("accent") or "").strip()
    if not re.fullmatch(r"#[0-9a-fA-F]{6}", accent):
        palette = ["#0F766E", "#7C3AED", "#B45309", "#BE123C", "#166534", "#1D4ED8", "#6D28D9", "#A21CAF"]
        accent = palette[sum(ord(c) for c in biz) % len(palette)]
    try:
        radius = max(0, min(22, int(d.get("radius"))))
    except Exception:
        radius = 14
    font = str(d.get("font") or "sans").lower()
    if font not in ("sans", "serif", "mono"):
        font = "sans"
    header = str(d.get("header") or "underline").lower()
    if header not in ("bar", "underline", "badge"):
        header = "underline"
    density = str(d.get("density") or "airy").lower()
    if density not in ("airy", "compact"):
        density = "airy"

    meta.update({"visitor": visitor, "business": biz, "title": title, "kind": kind,
                 "design": {"accent": accent, "radius": radius, "font": font,
                            "header": header, "density": density},
                 "source": source, "created": int(time.time())})
    output = {"rows": [{"code": "app-" + visitor, "label": title,
                        "ordinal": int(time.time()), "meta": meta}]}
