# Distro Bot Distro Scripts

> The distro.py helper, copied out by the install command in distro-setup. Never read or retype it.

- Skill: `brokep/distro-bot-distro-scripts` (Agent Skill)
- Install (CLI): `npx get-skill add brokep/distro-bot-distro-scripts`
- Raw SKILL.md: https://api.skillmd.com/api/skills/brokep/distro-bot-distro-scripts/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: brokep (https://skillmd.com/u/brokep)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/brokep/distro-bot-distro-scripts

---

# distro-scripts

# distro-scripts

The distro.py helper. The install command in distro-setup copies it out by its marker, so never read or retype it. Commands: install, init, status, set, ingest, report, winners, propose, approve, applied, revert, reject, changes, learn, playbook, site, scan, topic, topics, lead, leads, suppress, fal, higgs, grok, sizes. Each prints one JSON line.

```python
#!/usr/bin/env python3
# DISTRO_TOOLS_V1: Distro Bot helper: settings, performance ingest and analysis, the change ledger and budget caps,
# the playbook, site snapshots, topic scans, the outbound ledger, and ad creative on FAL, Higgsfield, or Grok Imagine.
# Every command prints one JSON line. Standard library only, plus ffmpeg for ad sizes.
import base64
import calendar
import csv
import datetime as dt
import email.utils
import html
import json
import math
import mimetypes
import os
import random
import re
import shutil
import statistics
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser

mimetypes.add_type("image/webp", ".webp")
# A user's bots share /workspace, so every file lives beside this script in the folder the install picked.
HOME = os.environ.get("DISTRO_HOME") or os.path.dirname(os.path.abspath(__file__))
P = {k: os.path.join(HOME, v) for k, v in (("state", "state.json"), ("perf", "perf.csv"), ("changes", "changes.jsonl"),
                                           ("playbook", "playbook.md"), ("topics", "topics.jsonl"), ("leads", "leads.csv"),
                                           ("sends", "sends.csv"), ("suppress", "suppress.txt"))}
ENV = os.environ.get
FAL_QUEUE, FAL_API, FAL_REST = ENV("DISTRO_FAL_QUEUE", "https://queue.fal.run"), ENV("DISTRO_FAL_API", "https://api.fal.ai"), ENV("DISTRO_FAL_REST", "https://rest.alpha.fal.ai")
XAI_API, HF_API = ENV("DISTRO_XAI_API", "https://api.x.ai/v1"), ENV("DISTRO_HF_API", "https://api.higgsfield.ai")
HN_API, NEWS_RSS = ENV("DISTRO_HN_API", "https://hn.algolia.com/api/v1"), ENV("DISTRO_NEWS_RSS", "https://news.google.com/rss/search")
SECRET_FILES = [p for p in (ENV("DISTRO_SECRETS", ""), "/home/box/agent-data/box-secrets.json") if p]
KEYS = ("FAL_KEY", "XAI_API_KEY", "HF_KEY")
UA = "Mozilla/5.0 (X11; Linux x86_64) distro-bot/1.0"
ROUTINES = ("Campaign check", "Trend scan", "Outbound replies", "Weekly distro review")
ROLES, ACCESS = ("sales", "voice", "intel", "seo", "qa"), ("connector", "browser", "export", "off")
SPEND_KINDS = ("budget", "bid", "launch", "pause")
KINDS = SPEND_KINDS + ("creative", "targeting")
LEARN_KINDS = ("hook", "angle", "offer", "audience", "format", "channel", "timing", "voice", "avoid", "other")
STAGES = ("new", "drafted", "sent", "replied", "handed_off", "closed")
STOP_WHY = ("optout", "bounce", "customer", "no", "other")
GAPS, MIN_IMPR = (3, 5, 7), 1000
FIELDS = ["date", "platform", "campaign", "adset", "ad", "spend", "impressions", "clicks", "conversions", "revenue",
          "engagements", "reach", "currency", "source", "read_at"]
NUMS = FIELDS[5:12]
LEAD_FIELDS = ["email", "name", "company", "title", "domain", "source", "stage", "step", "last_touch", "next_touch",
               "thread", "said", "replied_at", "handed_to", "note", "added"]
FREE_MAIL = set("gmail.com googlemail.com yahoo.com outlook.com hotmail.com live.com icloud.com me.com aol.com proton.me "
                "protonmail.com gmx.com mail.com yandex.com zoho.com".split())
ALIASES = {"facebook": "meta", "instagram": "meta", "meta ads": "meta", "google ads": "google", "adwords": "google",
           "twitter": "x", "x ads": "x", "x posts": "x-organic", "x organic": "x-organic", "linkedin ads": "linkedin",
           "tiktok ads": "tiktok", "reddit ads": "reddit", "bing": "microsoft", "microsoft ads": "microsoft"}
FORBIDDEN_INPUT = re.compile(r"(api_?key|token|secret|password)", re.I)
GROK_IMAGE, GROK_VIDEO = "grok-imagine-image-2.0", "grok-imagine-video-1.5"
HF_IMAGE, HF_VIDEO = "higgsfield-ai/soul/v2/standard", "bytedance/seedance-2.0/image-to-video"
# xAI list prices per second of video on 2026-10-01. /v1/models returns live image prices but none for video.
GROK_VIDEO_USD = {"grok-imagine-video": 0.05, "grok-imagine-video-1.5": 0.08}
PLACEMENTS = {"meta": [("square", 1080, 1080), ("portrait", 1080, 1350), ("story", 1080, 1920)],
              "google": [("square", 1200, 1200), ("landscape", 1200, 628), ("portrait", 960, 1200)],
              "x": [("square", 1200, 1200), ("landscape", 1200, 628)],
              "linkedin": [("square", 1200, 1200), ("landscape", 1200, 628)],
              "tiktok": [("story", 1080, 1920)],
              "reddit": [("square", 1200, 1200), ("portrait", 1080, 1350), ("landscape", 1920, 1080)]}
REPAIRED = []  # tools reinstalled after a computer update dropped them


# ---------- basics ----------

def now_dt():
    v = ENV("DISTRO_NOW")
    d = dt.datetime.fromisoformat(v.replace("Z", "+00:00")) if v else dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
    return d if d.tzinfo else d.replace(tzinfo=dt.timezone.utc)


def now():
    return now_dt().isoformat()


def today():
    return dt.date.fromisoformat(ENV("DISTRO_TODAY")) if ENV("DISTRO_TODAY") else dt.date.today()


def emit(**data):
    if REPAIRED:
        data.setdefault("repaired", REPAIRED)
    print(json.dumps(data, ensure_ascii=False, default=str))


def die(message, **extra):
    emit(error=message, **extra)
    sys.exit(1)


def opts_of(args):
    opts, rest, i = {}, [], 0
    while i < len(args):
        if args[i].startswith("--"):
            key, vals = args[i][2:], []
            while i + 1 < len(args) and not args[i + 1].startswith("--"):
                vals.append(args[i + 1])
                i += 1
            opts[key] = vals[0] if len(vals) == 1 else (vals or True)
        else:
            rest.append(args[i])
        i += 1
    return opts, rest


def topt(opts, key):
    v = opts.get(key)
    return " ".join(v) if isinstance(v, list) else v if isinstance(v, str) else ""


def fopt(opts, key, default=None):
    v = topt(opts, key)
    if not v:
        return default
    try:
        return float(v)
    except ValueError:
        die("--%s must be a number" % key)


def r2(v):
    return None if v is None else round(v, 2)


def div(a, b):
    return round(a / b, 2) if b else None


def pct(a, b):
    return round(100.0 * a / b, 2) if b else None


def fmtnum(v):
    return ("%.6f" % v).rstrip("0").rstrip(".")


def slug(text, n=40):
    return re.sub(r"[^a-z0-9]+", "-", str(text).lower()).strip("-")[:n].rstrip("-") or "item"


def num(v):
    if v is None or isinstance(v, (int, float)):
        return None if v is None else float(v)
    s = re.sub(r"^[^\d\-.]+", "", str(v).strip().replace(",", "").replace("\u00a0", "")).rstrip("%").strip()
    try:
        return float(s)
    except ValueError:
        return None


def parse_date(s, dayfirst=False):
    if isinstance(s, dt.date):
        return s
    s = str(s or "").strip()
    try:
        m = re.match(r"(\d{4})-(\d{1,2})-(\d{1,2})", s)
        if m:
            return dt.date(int(m[1]), int(m[2]), int(m[3]))
        m = re.match(r"(\d{1,2})/(\d{1,2})/(\d{2,4})", s)
        if m:
            a, b, y = int(m[1]), int(m[2]), int(m[3])
            return dt.date(y + 2000 if y < 100 else y, *((b, a) if dayfirst else (a, b)))
    except ValueError:
        return None
    for fmt in ("%b %d, %Y", "%B %d, %Y", "%d %b %Y", "%Y/%m/%d"):
        try:
            return dt.datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    w = parse_when(s)
    return w.date() if w else None


def parse_when(s):
    """A timestamp from ISO, RFC 822, or epoch text, as an aware datetime, or None."""
    s = str(s or "").strip()
    if not s:
        return None
    try:
        d = dt.datetime.fromtimestamp(float(s), dt.timezone.utc) if re.fullmatch(r"\d{9,10}(\.\d+)?", s) else \
            dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
    except ValueError:
        try:
            d = email.utils.parsedate_to_datetime(s)
        except (TypeError, ValueError, IndexError):
            try:
                d = dt.datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
            except ValueError:
                return None
    return d if d.tzinfo else d.replace(tzinfo=dt.timezone.utc)


def jsonl(path):
    out = []
    if os.path.exists(path):
        for line in open(path, encoding="utf-8"):
            try:
                out.append(json.loads(line))
            except ValueError:
                continue
    return out


def write_jsonl(path, items):
    with open(path + ".tmp", "w", encoding="utf-8") as f:
        f.writelines(json.dumps(i, ensure_ascii=False) + "\n" for i in items)
    os.replace(path + ".tmp", path)


def next_id(items, prefix):
    return prefix + str(max([int(i["id"][1:]) for i in items if re.fullmatch(prefix + r"\d+", i.get("id", ""))], default=0) + 1)


# ---------- secrets, http, tools ----------

def secret(name):
    value = ENV(name, "").strip()
    for path in SECRET_FILES:
        if value:
            break
        try:
            data = json.load(open(path, encoding="utf-8"))
            value = str((data.get("card") or {}).get(name) or data.get(name) or "").strip()
        except (OSError, ValueError, AttributeError):
            continue
    return value


def scrub(text):
    for k in KEYS:
        v = secret(k)
        for part in ([v] + [p for p in v.split(":") if len(p) >= 8]) if v else []:
            text = text.replace(part, "[" + k + "]")
    return text


def http(method, url, body=None, headers=None, raw=None, timeout=60):
    h = {"User-Agent": "distro-bot", "Accept": "application/json", **(headers or {})}
    if body is not None:
        raw, h["Content-Type"] = json.dumps(body).encode(), "application/json"
    try:
        with urllib.request.urlopen(urllib.request.Request(url, data=raw, method=method, headers=h), timeout=timeout) as r:
            code, data = r.status, r.read()
    except urllib.error.HTTPError as err:
        code, data = err.code, err.read()
    except (urllib.error.URLError, OSError) as err:
        return 0, {"detail": scrub(str(err))[:160]}
    try:
        return code, json.loads(data.decode() or "{}")
    except (ValueError, UnicodeDecodeError):
        return code, {"detail": data[:200].decode("utf-8", "replace")}


def fetch_text(url, limit=3 << 20):
    req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "en-US,en;q=0.8"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            raw, final, code, ctype = r.read(limit), r.geturl(), r.status, r.headers.get("Content-Type", "")
    except urllib.error.HTTPError as err:
        return err.code, url, ""
    except (urllib.error.URLError, OSError, ValueError) as err:
        return 0, url, str(err)[:160]
    m = re.search(r"charset=([\w-]+)", ctype)
    try:
        return code, final, raw.decode(m[1] if m else "utf-8", "replace")
    except LookupError:
        return code, final, raw.decode("utf-8", "replace")


def download(url, dest, limit=500 << 20):
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    if url.startswith("data:"):
        head, _, payload = url.partition(",")
        open(dest, "wb").write(base64.b64decode(payload) if ";base64" in head else urllib.parse.unquote_to_bytes(payload))
        return
    with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "distro-bot"}), timeout=300) as r, open(dest, "wb") as f:
        total = 0
        for chunk in iter(lambda: r.read(1 << 20), b""):
            total += len(chunk)
            if total > limit:
                raise OSError("file over the download limit")
            f.write(chunk)


def repair_tools():
    """An image update of the computer drops apt packages, so reinstall ffmpeg when it is gone."""
    if all(shutil.which(t) for t in ("ffmpeg", "ffprobe")):
        return ""
    if ENV("DISTRO_APT"):
        cmd = [ENV("DISTRO_APT")]
    elif not shutil.which("apt-get"):
        return "no apt-get on this computer"
    else:
        cmd = ["apt-get"] if os.geteuid() == 0 else ["sudo", "-n", "apt-get"] if shutil.which("sudo") else None
        if not cmd:
            return "not root and no sudo"
    for args in (["update", "-qq"], ["install", "-y", "-qq", "ffmpeg"]):
        try:
            r = subprocess.run(cmd + args, capture_output=True, text=True, timeout=900, env={**os.environ, "DEBIAN_FRONTEND": "noninteractive"})
        except (OSError, subprocess.TimeoutExpired) as err:
            return str(err)[:160]
        if r.returncode:
            return ((r.stderr or r.stdout).strip().splitlines() or ["apt-get failed"])[-1][:160]
    if shutil.which("ffmpeg"):
        REPAIRED.append("ffmpeg")
    return ""


def ff(cmd):
    if not shutil.which("ffmpeg"):
        err = repair_tools()
        if not shutil.which("ffmpeg"):
            die("ffmpeg is missing, likely dropped by a computer update, and reinstalling it failed: " + (err or "not found"))
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
    if r.returncode:
        die(cmd[0] + " failed", detail=r.stderr.strip().splitlines()[-3:])
    return r


# ---------- state ----------

def fresh_state():
    return {"version": 1, "created": now(), "setup": "step 1", "product": "", "site": "", "audience": "", "goal": "",
            "conversion": "", "currency": "USD", "monthly_cap": 0.0, "daily_cap": 0.0, "max_step_pct": 20, "autopilot": False,
            "creative_cap": 2.0, "media": "", "send_cap": 20, "steps": 3, "keywords": [], "competitors": [], "platforms": {},
            "teammates": {}, "routines_on": [], "last": {}, "jobs": {}}


def load():
    if not os.path.exists(P["state"]):
        die("no state yet, run: distro.py init")
    s = json.load(open(P["state"], encoding="utf-8"))
    for k, v in fresh_state().items():
        s.setdefault(k, v)
    return s


def save(s):
    os.makedirs(HOME, exist_ok=True)
    json.dump(s, open(P["state"] + ".tmp", "w", encoding="utf-8"), indent=1, ensure_ascii=False)
    os.replace(P["state"] + ".tmp", P["state"])


def cmd_install(a):
    base, home, n = ENV("DISTRO_BASE", "/workspace"), ENV("DISTRO_DIR", ""), 1
    default = os.path.join(base, "distro-bot")
    while not home:
        d = default + ("-%d" % n if n > 1 else "")
        home, n = ("" if os.path.exists(os.path.join(d, "state.json")) else d), n + 1
    code = open(os.path.abspath(__file__), encoding="utf-8").read()
    compile(code, "distro.py", "exec")
    os.makedirs(home, exist_ok=True)
    dest = os.path.join(home, "distro.py")
    if os.path.abspath(__file__) != dest:
        open(dest, "w", encoding="utf-8").write(code)
    err = repair_tools()
    moved = home != default and not ENV("DISTRO_DIR")
    emit(ok=True, installed=dest, home=home, moved=moved, ffmpeg=bool(shutil.which("ffmpeg")), tool_error=err,
         note="Another Distro Bot owns %s, so rewrite your STATE memory line to python3 %s" % (default, dest) if moved else "")


def cmd_init(a):
    existed = os.path.exists(P["state"])
    if not existed:
        save(fresh_state())
    emit(ok=True, existed=existed, home=HOME, setup=load()["setup"])


def resume_cmd(rid, job):
    return {"xai": "distro.py grok result " + rid, "higgs": "distro.py higgs result " + rid}.get(
        job.get("provider"), "distro.py fal result %s %s" % (job.get("endpoint"), rid))


def latest(rows):
    out = {}
    for r in rows:
        out[r["platform"]] = max(out.get(r["platform"], r["date"]), r["date"])
    return out


def cmd_status(a):
    s, rows, ch, leads, t = load(), read_perf(), jsonl(P["changes"]), read_leads(), today()
    emit(home=HOME, setup=s["setup"], **{k: s[k] for k in ("product", "site", "audience", "goal", "conversion", "currency")},
         caps={"monthly": s["monthly_cap"], "daily": s["daily_cap"], "max_step_pct": s["max_step_pct"]},
         autopilot=s["autopilot"], creative_cap=s["creative_cap"], media=s["media"], keys={k: bool(secret(k)) for k in KEYS},
         **{k: s[k] for k in ("platforms", "teammates", "routines_on", "keywords", "competitors", "last")},
         spend=spend_numbers(s, rows, frame=t) if rows else None,
         freshness={p: {"latest": d.isoformat(), "days_old": (t - d).days} for p, d in sorted(latest(rows).items())},
         changes={"waiting_yes": sum(c["status"] == "proposed" and c["lane"] == "ask" for c in ch),
                  "approved_not_applied": sum(c["status"] == "approved" for c in ch),
                  "autopilot_ready": sum(c["status"] == "proposed" and c["lane"] == "autopilot" for c in ch)},
         media_jobs_pending=[{"id": k, "resume": resume_cmd(k, j)} for k, j in s["jobs"].items() if j.get("status") not in ("COMPLETED", "FAILED")],
         leads={"due": len(due_leads(s, leads)), "replied_not_handed": sum(x["stage"] == "replied" for x in leads),
                "sent_today": sends_on(t), "send_cap": s["send_cap"], "steps": s["steps"]},
         topics_new=sum(x.get("status") == "new" for x in jsonl(P["topics"])),
         playbook_entries=sum(len(v) for v in read_playbook().values()), ffmpeg=bool(shutil.which("ffmpeg")))


SET_TEXT = ("setup", "product", "site", "audience", "goal", "conversion")
SET_NUM = {"monthly_cap": (0, 1e9, float), "daily_cap": (0, 1e9, float), "creative_cap": (0, 1e6, float),
           "max_step_pct": (1, 100, int), "send_cap": (0, 500, int), "steps": (1, 6, int)}


def cmd_set(a):
    if len(a) < 2:
        die("usage: distro.py set <key> <value>. Keys: %s, %s, currency, autopilot on|off, media fal|higgs|grok|none, keywords a,b, "
            "competitors a,b, platform <name> <%s> [account], teammate <%s> <id or name|none>, routine \"<name>\" on|off, last <name>"
            % (", ".join(SET_TEXT), ", ".join(SET_NUM), "|".join(ACCESS), "|".join(ROLES)))
    s, key, rest = load(), a[0], a[1:]
    value, out = " ".join(rest).strip(), {}
    if key in SET_TEXT:
        s[key] = value
    elif key in SET_NUM:
        lo, hi, kind = SET_NUM[key]
        v = num(value)
        if v is None or not lo <= v <= hi:
            die("%s must be a number from %s to %s" % (key, lo, int(hi)))
        s[key] = kind(round(v, 2))
        if key == "monthly_cap" and v and not s["daily_cap"]:
            s["daily_cap"] = out["daily_cap"] = round(v / 30.0, 2)
    elif key == "currency" and re.fullmatch(r"[A-Za-z]{3}", value):
        s[key] = value.upper()
    elif key == "autopilot" and value.lower() in ("on", "off"):
        s[key] = value.lower() == "on"
    elif key == "media" and value in ("fal", "higgs", "grok", "none"):
        s[key] = value
    elif key in ("keywords", "competitors"):
        s[key] = [x.strip() for x in value.split(",") if x.strip()]
    elif key == "platform" and len(rest) >= 2 and rest[1] in ACCESS:
        name = out["platform"] = norm_platform(rest[0])
        s["platforms"].pop(name, None)
        if rest[1] != "off":
            s["platforms"][name] = {"access": rest[1], "account": " ".join(rest[2:]), "since": today().isoformat()}
    elif key == "teammate" and rest[0] in ROLES:
        who = " ".join(rest[1:]).strip()
        s["teammates"].pop(rest[0], None)
        if who.lower() not in ("", "none", "off"):
            s["teammates"][rest[0]] = who
    elif key == "routine" and len(rest) >= 2 and rest[-1] in ("on", "off"):
        name = next((r for r in ROUTINES if r.lower() == " ".join(rest[:-1]).strip().strip('"').lower()), None)
        if not name:
            die("routines: " + ", ".join(ROUTINES))
        s["routines_on"] = [r for r in s["routines_on"] if r != name] + ([name] if rest[-1] == "on" else [])
    elif key == "last":
        s["last"][slug(value, 20)] = now()
    else:
        die("bad setting: %s %s. Run distro.py set for the keys and values." % (key, value))
    save(s)
    emit(ok=True, key=key, value={"platform": s["platforms"], "teammate": s["teammates"], "routine": s["routines_on"],
                                  "last": s["last"]}.get(key, s.get(key)), **out)


# ---------- performance data ----------

PREFIXES = ("public metrics ", "non public metrics ", "organic metrics ", "promoted metrics ", "metrics ", "segments ", "insights ")
SYN = [("date", "date|day|reporting starts|date start|start date|start date in utc|gregorian date|by day|created at|time period"),
       ("campaign", "campaign name|campaign|campaign title"),
       ("adset", "ad set name|ad set|adset name|adset|ad group name|ad group|adgroup name|adgroup|line item name|line item|ad squad name|ad squad"),
       ("ad", "ad name|ad|creative name|creative|promoted tweet|tweet text|post text|text|tweet|post|tweet id|post id|id"),
       ("spend", "amount spent|spend|cost|total spent|billed charge local micro|cost micros|costmicros|spend micros"),
       ("impressions", "impressions|impression count|impression|impr"),
       ("clicks", "link clicks|url link clicks|url clicks|inline link clicks|outbound clicks|clicks destination|clicks|clicks all"),
       ("conversions", "conversions|results|website purchases|purchases|leads|website leads|sign ups|signups|registrations completed|complete registration|all conv|conv"),
       ("revenue", "conversion value|conversions value|conversionsvalue|purchases conversion value|website purchases conversion value|purchase value|total conversion value|conv value|revenue|value"),
       ("engagements", "engagements|total engagements|post engagements|engagement count"),
       ("reach", "reach"), ("currency", "currency|account currency|currency code")]
ENGAGE_PARTS = set("like count|likes|retweet count|repost count|retweets|reposts|reply count|replies|quote count|quotes|bookmark count|bookmarks".split("|"))
SPEND_RE = re.compile(r"^(amount spent|spend|total spent|cost)( [a-z]{3})?$")
TEXT_AD = ("tweet text", "post text", "text")


def norm_header(h):
    h = re.sub(r"[^a-z0-9]+", " ", re.sub(r"([a-z])([A-Z])", r"\1 \2", str(h)).lower()).strip()
    for _ in range(3):
        for p in PREFIXES:
            if h.startswith(p) and len(h) > len(p):
                h = h[len(p):]
    return h


def norm_platform(p):
    p = re.sub(r"[\s_-]+", " ", str(p).strip().lower())
    if p not in ALIASES and p.endswith(" ads"):
        p = p[:-4]
    return ALIASES.get(p, p).replace(" ", "-")


def map_headers(headers):
    normed, mapping = {h: norm_header(h) for h in headers}, {}
    for field, syns in SYN:
        for syn in syns.split("|"):
            hit = next((h for h, n in normed.items() if (n == syn or field == "spend" and SPEND_RE.match(n)) and h not in mapping.values()), None)
            if hit is not None:
                mapping[field] = hit
                break
    parts = [h for h, n in normed.items() if n in ENGAGE_PARTS and h not in mapping.values()]
    return mapping, parts, [h for h in headers if h not in mapping.values() and h not in parts]


def flatten(d, prefix=""):
    out = {}
    for k, v in d.items():
        key = "%s.%s" % (prefix, k) if prefix else str(k)
        if isinstance(v, dict):
            out.update(flatten(v, key))
        elif not isinstance(v, list):
            out[key] = v
    return out


def read_table(path, plain=False):
    text = open(path, encoding="utf-8-sig", errors="replace").read()
    if not plain and text.lstrip()[:1] in ("[", "{"):
        data = json.loads(text)
        if isinstance(data, dict):
            data = next((data[k] for k in ("data", "rows", "results", "items", "posts") if isinstance(data.get(k), list)), [data])
        rows = [flatten(x) for x in data if isinstance(x, dict)]
        return list(dict.fromkeys(k for r in rows for k in r)), rows
    lines = text.splitlines()
    delim = max("\t,;", key=lambda d: sum(ln.count(d) for ln in lines[:6]))
    start = 0 if plain else next((i for i, ln in enumerate(lines[:12]) if len(map_headers(next(csv.reader([ln], delimiter=delim), []))[0]) >= 2), 0)
    reader = csv.DictReader(lines[start:], delimiter=delim)
    return reader.fieldnames or [], [r for r in reader if any(isinstance(v, str) and v.strip() for v in r.values())]


def read_perf():
    out = []
    if os.path.exists(P["perf"]):
        for r in csv.DictReader(open(P["perf"], newline="", encoding="utf-8")):
            row = {k: r.get(k) or "" for k in FIELDS}
            row["date"] = parse_date(row["date"])
            if row["date"]:
                out.append({**row, **{k: num(row[k]) for k in NUMS}})
    return out


def write_perf(rows):
    rows.sort(key=lambda r: tuple(str(r[k]) for k in FIELDS[:5]))
    with open(P["perf"] + ".tmp", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=FIELDS)
        w.writeheader()
        for r in rows:
            w.writerow({k: r[k].isoformat() if k == "date" else ("" if r[k] is None else fmtnum(r[k])) if k in NUMS else r[k] for k in FIELDS})
    os.replace(P["perf"] + ".tmp", P["perf"])


def cmd_ingest(a):
    opts, args = opts_of(a)
    platform = norm_platform(topt(opts, "platform"))
    if not args or not os.path.isfile(args[0]) or not platform:
        die("usage: distro.py ingest <csv, tsv, or json> --platform <meta|google|x|linkedin|tiktok|reddit|x-organic|...> "
            "[--source \"connector 2026-10-01\"] [--date YYYY-MM-DD for a one-day file] [--dayfirst]")
    headers, table = read_table(args[0])
    mapping, parts, unmapped = map_headers(headers)
    fixed = parse_date(topt(opts, "date")) if topt(opts, "date") else None
    if "date" not in mapping and not fixed:
        die("no date column. Export by day, or pass --date YYYY-MM-DD for a one-day file", columns=headers[:30])
    if not ({"spend", "impressions", "engagements"} & set(mapping)) and not parts:
        die("found no spend, impressions, or engagement columns", columns=headers[:30])
    micro = "micro" in norm_header(mapping.get("spend", ""))
    id_col = next((h for h in headers if norm_header(h) in ("id", "tweet id", "post id")), None) \
        if norm_header(mapping.get("ad", "")) in TEXT_AD else None
    get = lambda raw, f: raw.get(mapping[f]) if f in mapping else None  # noqa: E731
    existing = {tuple(r[k] for k in FIELDS[:5]): r for r in read_perf()}
    added = replaced = skipped = 0
    dates, spend, currencies, camps, stamp = [], 0.0, set(), set(), now()
    for raw in table:
        camp = str(get(raw, "campaign") or "").strip()
        d = parse_date(get(raw, "date"), bool(opts.get("dayfirst"))) if "date" in mapping else fixed
        if not d or str(next(iter(raw.values()), "") or "").strip().lower().startswith("total") or camp.lower().startswith("total"):
            skipped += 1
            continue
        ad = " ".join(str(get(raw, "ad") or "").split())
        if id_col and raw.get(id_col):
            ad = "%s %s" % (raw[id_col], ad[:50])
        row = {"date": d, "platform": platform, "campaign": camp or ("(all)" if "spend" in mapping else "organic"),
               "adset": str(get(raw, "adset") or "").strip(), "ad": ad.strip()[:120], **{k: num(get(raw, k)) for k in NUMS},
               "currency": str(get(raw, "currency") or "").strip().upper(), "source": topt(opts, "source") or "file " + os.path.basename(args[0]),
               "read_at": stamp}
        if micro and row["spend"] is not None:
            row["spend"] /= 1e6
        vals = [num(raw.get(h)) for h in parts]
        if row["engagements"] is None and any(v is not None for v in vals):
            row["engagements"] = sum(v for v in vals if v is not None)
        key = tuple(row[k] for k in FIELDS[:5])
        replaced, added = replaced + (key in existing), added + (key not in existing)
        existing[key] = row
        dates.append(d)
        spend += row["spend"] or 0
        camps.add(row["campaign"])
        currencies |= {row["currency"]} - {""}
    if not dates:
        die("no rows with a readable date", columns=headers[:30], skipped=skipped)
    write_perf(list(existing.values()))
    warnings = [w for c, w in (("spend" not in mapping, "no spend column, so cost metrics are blank for these rows"),
                               ("conversions" not in mapping and "spend" in mapping, "no results column, so cost per result is blank"),
                               (len(currencies) > 1, "several currencies: " + ", ".join(sorted(currencies)))) if c]
    emit(ok=True, platform=platform, added=added, replaced=replaced, skipped=skipped, start=min(dates), end=max(dates),
         campaigns=len(camps), spend=r2(spend), currency=sorted(currencies), mapped=mapping, engagement_parts=parts,
         unmapped=unmapped[:20], warnings=warnings)


# ---------- analysis ----------

def sums(rows):
    return {k: sum(r[k] for r in rows if r[k] is not None) for k in NUMS}


def kpis(s):
    sp, im, cl, cv, rv, en = (s[k] for k in ("spend", "impressions", "clicks", "conversions", "revenue", "engagements"))
    return {"spend": r2(sp), "impressions": int(im), "clicks": int(cl), "conversions": r2(cv), "ctr": pct(cl, im), "cpc": div(sp, cl),
            "cpm": div(sp * 1000, im), "cvr": pct(cv, cl), "cpa": div(sp, cv), "revenue": r2(rv) or None,
            "roas": div(rv, sp) if rv else None, "er": pct(en, im) if en else None}


def delta(cur, prev):
    return {k: round(100.0 * (cur[k] - prev[k]) / prev[k], 1) for k in ("spend", "conversions", "ctr", "cpc", "cpm", "cvr", "cpa", "roas", "er")
            if cur.get(k) is not None and prev.get(k)}


def group(rows, keys):
    g = {}
    for r in rows:
        g.setdefault(tuple(r[k] for k in keys), []).append(r)
    return g


def paid(rows):
    return [r for r in rows if (r["spend"] or 0) > 0]


def daily(rows):
    return {d: sums(v) for (d,), v in group(rows, ["date"]).items()}


def prob_best(arms, draws=4000):
    """Chance each arm (successes, trials) has the highest true rate, from Beta(1,1) posteriors."""
    rnd, wins = random.Random(7), [0] * len(arms)
    for _ in range(draws):
        vals = [rnd.betavariate(x + 1, max(n - x, 0) + 1) for x, n in arms]
        wins[vals.index(max(vals))] += 1
    return [round(w / draws, 3) for w in wins]


def spend_numbers(s, rows, end=None, frame=None):
    """Month pacing. end is the last day with data, frame picks the month: today for a live change, end for a report."""
    end = end or (max(r["date"] for r in rows) if rows else today())
    frame, pr = frame or end, paid(rows)
    start, through = frame.replace(day=1), min(end, frame)
    days_in = calendar.monthrange(frame.year, frame.month)[1]
    remaining = days_in - through.day if through >= start else days_in
    mtd = sum(r["spend"] for r in pr if start <= r["date"] <= through)
    recent = [r for r in pr if end - dt.timedelta(days=6) <= r["date"] <= end]
    days = len({r["date"] for r in recent})
    rate = sum(r["spend"] for r in recent) / days if days else 0.0
    room = (s["monthly_cap"] - mtd) / remaining - rate if s["monthly_cap"] and remaining > 0 else None
    return {"month": frame.strftime("%Y-%m"), "as_of": end.isoformat(), "currency": s["currency"], "month_to_date": r2(mtd),
            "run_rate_per_day": r2(rate), "projected_month": r2(mtd + rate * remaining), "monthly_cap": s["monthly_cap"],
            "daily_cap": s["daily_cap"], "remaining_days": remaining, "room_per_day": r2(room)}


def anomalies(rows, end):
    flags, day = [], lambda i: end - dt.timedelta(days=i)
    for (plat, camp), rs in group(paid(rows), ["platform", "campaign"]).items():
        ser, where = daily(rs), "%s / %s" % (plat, camp)
        base = [ser[day(i)] for i in range(1, 15) if day(i) in ser]
        last = ser.get(end)
        if len(base) >= 7 and last:
            sp = [b["spend"] for b in base]
            mean, sd = statistics.mean(sp), statistics.pstdev(sp)
            if last["spend"] > max(2 * mean, mean + 3 * sd) and last["spend"] - mean >= 5:
                flags.append({"type": "spend_spike", "where": where, "detail": "spent %.2f on %s against a 14-day average of %.2f" % (last["spend"], end, mean)})
        bconv, bspend = sum(b["conversions"] for b in base), sum(b["spend"] for b in base)
        recent = [ser[day(i)] for i in range(3) if day(i) in ser]
        rconv, rspend = sum(x["conversions"] for x in recent), sum(x["spend"] for x in recent)
        if bconv >= 10 and recent and rspend >= 0.5 * len(recent) * bspend / len(base):
            rcpa = rspend / rconv if rconv else float("inf")
            if rcpa >= 1.5 * bspend / bconv:
                flags.append({"type": "cpa_jump", "where": where, "detail": "cost per result %s over the last %d days against %.2f before" %
                              ("with no results" if not rconv else "%.2f" % rcpa, len(recent), bspend / bconv)})
        if bconv >= 7 and all(x and x["spend"] > 0 and not x["conversions"] for x in (ser.get(end), ser.get(day(1)))):
            flags.append({"type": "conversions_stopped", "where": where,
                          "detail": "spend kept going with no results for 2 days. Check tracking, the landing page, and checkout"})
    return flags


def fatigue(rows, end):
    out = []
    for key, rs in group([r for r in rows if r["ad"] and r["date"] <= end], ["platform", "campaign", "adset", "ad"]).items():
        ser = daily(rs)
        days = sorted(ser)
        if len(days) < 10:
            continue
        first, last = sums([{**ser[d], "date": d} for d in days[:7]]), sums([{**ser[d], "date": d} for d in days[-3:]])
        if min(first["impressions"], last["impressions"]) < MIN_IMPR:
            continue
        c1, c2 = first["clicks"] / first["impressions"], last["clicks"] / last["impressions"]
        if c1 and c2 <= 0.7 * c1:
            out.append({"where": "%s / %s / %s" % (key[0], key[1], key[3]), "ctr_first_week": round(100 * c1, 2), "ctr_last_3_days": round(100 * c2, 2),
                        "drop_pct": round(100 * (1 - c2 / c1), 1), "frequency_last_3_days": div(last["impressions"], last["reach"])})
    return out


def ad_tests(rows):
    tests, early = [], 0
    for (plat, camp, adset), rs in group([r for r in paid(rows) if r["ad"]], ["platform", "campaign", "adset"]).items():
        ads = [(ad, sums(v)) for (ad,), v in group(rs, ["ad"]).items()]
        if len(ads) < 2:
            continue
        if sum(s["conversions"] for _, s in ads) >= 20:
            metric, arms = "results per impression", [(s["conversions"], s["impressions"]) for _, s in ads]
        elif all(s["impressions"] >= MIN_IMPR for _, s in ads):
            metric, arms = "ctr (clicks, not results)", [(s["clicks"], s["impressions"]) for _, s in ads]
        else:
            early += 1
            continue
        items = sorted(({"ad": ad, "rate_pct": pct(x, n), "impressions": int(n), "p_best": p}
                        for (ad, _), (x, n), p in zip(ads, arms, prob_best([(int(x), int(n)) for x, n in arms]))), key=lambda i: -i["p_best"])
        tests.append({"where": "%s / %s / %s" % (plat, camp, adset or "-"), "metric": metric, "ads": items,
                      "winner": items[0]["ad"] if items[0]["p_best"] >= 0.95 else None,
                      "losers": [i["ad"] for i in items if i["p_best"] <= 0.05 and i["impressions"] >= MIN_IMPR]})
    return tests, early


def build_report(s, rows, days, end, by):
    start = end - dt.timedelta(days=days - 1)
    pstart, pend = start - dt.timedelta(days=days), start - dt.timedelta(days=1)
    cur, prev = [r for r in rows if start <= r["date"] <= end], [r for r in rows if pstart <= r["date"] <= pend]
    pc, org = paid(cur), [r for r in cur if not (r["spend"] or 0) > 0]
    tot = kpis(sums(pc))
    keys = {"platform": ["platform"], "campaign": ["platform", "campaign"], "adset": ["platform", "campaign", "adset"],
            "ad": ["platform", "campaign", "adset", "ad"]}[by]
    pg = group(prev, keys)
    lines = sorted(({**dict(zip(keys, k)), **kpis(sums(v)), "change_pct": delta(kpis(sums(v)), kpis(sums(pg.get(k, []))))}
                    for k, v in group(cur, keys).items()), key=lambda g: -(g["spend"] or 0))
    total_sp, total_cv, channels = tot["spend"] or 0, tot["conversions"] or 0, []
    for (plat,), v in group(pc, ["platform"]).items():
        kp = kpis(sums(v))
        ss, cs = kp["spend"] / total_sp if total_sp else 0, (kp["conversions"] or 0) / total_cv if total_cv else None
        channels.append({"platform": plat, **kp, "spend_share_pct": round(100 * ss, 1), "result_share_pct": None if cs is None else round(100 * cs, 1),
                         "efficiency": round(cs / ss, 2) if cs is not None and ss else None})
    for (plat,), v in group(org, ["platform"]).items():
        kp = kpis(sums(v))
        channels.append({"platform": plat, "organic": True, "impressions": kp["impressions"], "clicks": kp["clicks"],
                         "engagements": int(sums(v)["engagements"]), "er": kp["er"], "ctr": kp["ctr"]})
    pacing, flags = spend_numbers(s, rows, end), []
    if pacing["monthly_cap"] and pacing["projected_month"] > pacing["monthly_cap"]:
        over = pacing["projected_month"] - pacing["monthly_cap"]
        flags.append({"type": "over_cap", "where": "all paid", "detail": "on pace to pass the monthly cap by %.2f, lower daily spend by "
                      "%.2f in total to land on it" % (over, over / max(pacing["remaining_days"], 1))})
    for d, v in sorted(daily(pc).items()):
        if pacing["daily_cap"] and v["spend"] > pacing["daily_cap"] * 1.1:
            flags.append({"type": "daily_cap", "where": d.isoformat(), "detail": "spent %.2f against a daily cap of %.2f" % (v["spend"], pacing["daily_cap"])})
    flags += anomalies(rows, end) + [{"type": "stale", "where": p, "detail": "latest numbers are from %s" % d}
                                     for p, d in latest(rows).items() if (today() - d).days > 2]
    tests, early = ad_tests(pc)
    fat = fatigue(rows, end)
    sugg = [{"kind": "creative", "what": "pause %s in %s" % (x, t["where"]), "why": "under 5%% chance of being the best ad on %s" % t["metric"]}
            for t in tests for x in t["losers"]]
    sugg += [{"kind": "creative", "what": "refresh the creative in " + f["where"], "why": "CTR down %s%% since its first week" % f["drop_pct"]} for f in fat]
    camps = sorted((dict(zip(["platform", "campaign"], k), **kpis(sums(v))) for k, v in group(pc, ["platform", "campaign"]).items()), key=lambda g: g["cpa"] or 1e18)
    camps = [g for g in camps if (g["conversions"] or 0) >= 5 and g["spend"] >= 0.05 * total_sp]
    if len(camps) >= 2 and camps[-1]["cpa"] >= 1.5 * camps[0]["cpa"]:
        move = min(0.2 * camps[-1]["spend"], s["max_step_pct"] / 100.0 * camps[0]["spend"]) / days
        sugg.append({"kind": "budget", "what": "move %.2f a day from %s to %s, total unchanged" % (move, camps[-1]["campaign"], camps[0]["campaign"]),
                     "why": "cost per result %.2f against %.2f" % (camps[-1]["cpa"], camps[0]["cpa"]), "needs": "the user's yes"})
    if pacing["room_per_day"] and pacing["projected_month"] < 0.85 * pacing["monthly_cap"]:
        sugg.append({"kind": "budget", "what": "room for %.2f a day more inside the cap" % pacing["room_per_day"], "needs": "the user's yes",
                     "why": "projected %.2f of %.2f" % (pacing["projected_month"], pacing["monthly_cap"])})
    caveats = [c for ok, c in (
        (sum(1 for c in channels if c.get("conversions")) > 1, "Results are platform-reported, so totals can count one customer twice across platforms."),
        (pc and total_cv < 30, "Fewer than 30 results in the window, so cost per result moves a lot by chance."),
        (len({r["currency"] for r in cur} - {""}) > 1, "Spend mixes currencies and totals are not converted."),
        (early, "%d ad set(s) are too early to call: each ad needs %d impressions, or 20 results across the ad set." % (early, MIN_IMPR))) if ok]
    return {"window": {"start": start.isoformat(), "end": end.isoformat(), "days": days, "compare_start": pstart.isoformat(),
                       "compare_end":

…(truncated)
