#!/usr/bin/env python3
"""Echo Space pilot client — the file we hand to pilot partners (reference client).

  export ECHOSPACE_API_KEY=es_pilot_...
  export ECHOSPACE_URL=https://api.echo-program.com

  # 1. verdict from SAMPLES (drawn here with a seed; the corpus stays on your machine)
  python3 echospace_pilot.py forecast --target target/ --pool pool/ --label run1 \
      [--model-params 7000000000 --keep 0.25 --language en --regime pretraining --content text] \
      [--table --out fc_run1.json]

  # 2. keep list computed LOCALLY over the whole pool from the returned scoring table
  python3 echospace_pilot.py select-local --forecast fc_run1.json --pool pool/ --keep 0.25 --out keep.json

  # 2s. the same for a pool too large for one process: score its shards in parallel, then cut once
  python3 echospace_pilot.py select-sharded --forecast fc_run1.json --pool pool/ --keep 0.25 --out keep/ --workers 16
  #     or, across machines: score each shard where it lives (no key, no network) ...
  python3 echospace_pilot.py score-shard --forecast fc_run1.json --shard pool/part-0007 --out scores/part-0007.npz
  #     ... then bring the small score files together and make the cut
  python3 echospace_pilot.py select-merge --forecast fc_run1.json --scores scores/ --keep 0.25 --out keep/

  # 2'. or, for small pools, let the service compute the keep list (uploads the whole pool)
  python3 echospace_pilot.py select --target target/ --pool pool/ --keep 0.25 --out keep.json

  # 3. the receipt
  python3 echospace_pilot.py outcome --forecast fc_xxxxxxxx --selected 1.91 --baseline 2.05 \
      [--model-params 7000000000 --train-tokens 2000000000 --keep 0.25 --architecture "decoder, 32 layers"]

  python3 echospace_pilot.py selftest      # checks this file's hashing against the service's vectors

A directory = one document per file (.txt/.md/.jsonl with a "text" field). A single file
is one document (.jsonl: one per line). Samples are sent over HTTPS gzip-compressed,
processed in memory and never stored by the service. Local selection needs numpy.

Sharded selection: a shard is any file or directory of documents; under `--pool`, every
entry directly inside the directory is one shard. Each shard gets its own keep file,
whose indices count documents inside that shard, in the order this client reads them.
The result does not depend on how many workers ran or in which order shards finished.
"""
import argparse, gzip, hashlib, json, os, random, re, ssl, sys, time, urllib.error, urllib.request, zlib

try:  # python.org builds on macOS ship without root certificates; certifi fixes that
    import certifi
    _CTX = ssl.create_default_context(cafile=certifi.where())
except ImportError:
    _CTX = ssl.create_default_context()

CLIENT = "echospace-pilot-client/0.4"
HASHER = "es-h1"
NH = 16384
URL = os.environ.get("ECHOSPACE_URL", "http://127.0.0.1:8787").rstrip("/")
KEY = os.environ.get("ECHOSPACE_API_KEY", "")
BUSY_TRIES = 9          # a busy service is retried for a few minutes, then reported
_WORD = re.compile(r"\S+")


# ---------------- documents (streamed; nothing is held that need not be) ----------------

def iter_docs(path):
    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            dirs.sort()                                   # the same order on every machine
            for f in sorted(files):
                yield from iter_docs(os.path.join(root, f))
        return
    if path.endswith(".jsonl"):
        with open(path, encoding="utf-8", errors="replace") as fh:
            for line in fh:
                if line.strip():
                    yield json.loads(line)["text"]
        return
    with open(path, encoding="utf-8", errors="replace") as fh:
        yield fh.read()


def count_docs(path):
    n = w = 0
    for d in iter_docs(path):
        n += 1; w += len(_WORD.findall(d))
    return n, w


def sample_docs(path, word_budget, seed):
    """Seeded random sample of whole documents whose total is about `word_budget` words.
    Two streaming passes: count, then keep the documents whose rank in a seeded
    permutation falls below the needed count. Returns (docs, total_documents)."""
    import numpy as np
    n, w = count_docs(path)
    if n == 0:
        sys.exit(f"no documents under {path}")
    if w <= word_budget:
        return list(iter_docs(path)), n
    k = max(1, int(round(n * word_budget / w)))
    rank = np.empty(n, dtype=np.int64)
    rank[np.random.default_rng(seed).permutation(n)] = np.arange(n)
    return [d for i, d in enumerate(iter_docs(path)) if rank[i] < k], n


# ---------------- HTTP ----------------

def call(ep, body=None, method=None):
    data = None
    headers = {"Authorization": f"Bearer {KEY}", "User-Agent": CLIENT}
    if body is not None:
        data = gzip.compress(json.dumps(body).encode(), compresslevel=6)
        headers.update({"Content-Type": "application/json", "Content-Encoding": "gzip"})
    req = urllib.request.Request(f"{URL}/v1/{ep}", method=method or ("POST" if body is not None else "GET"),
                                 headers=headers, data=data)
    for attempt in range(BUSY_TRIES):
        try:
            with urllib.request.urlopen(req, timeout=900, context=_CTX) as r:
                return json.load(r)
        except urllib.error.HTTPError as e:
            # 503 = the service is busy and recorded nothing; it says when to come back
            if e.code == 503 and attempt < BUSY_TRIES - 1:
                wait = e.headers.get("Retry-After", "")
                wait = (min(int(wait), 120) if wait.isdigit() else 15) + random.uniform(0, 5)   # spread the herd
                print(f"service busy, retrying in {wait:.0f} s ({attempt + 1}/{BUSY_TRIES - 1})", file=sys.stderr)
                time.sleep(wait)
                continue
            sys.exit(f"HTTP {e.code}: {e.read().decode()}")
        except urllib.error.URLError as e:
            if "CERTIFICATE_VERIFY_FAILED" in str(e):
                sys.exit("TLS certificate store missing on this Python: run `pip install certifi` "
                         "(or macOS 'Install Certificates.command') and retry")
            raise


# ---------------- local scoring (must match the service bit for bit; see selftest) --------

def word_hashes(text):
    return [zlib.crc32(t.encode("utf-8", "replace")) & 0xFFFFFFFF for t in _WORD.findall(text.lower())]


def buckets(text):
    hs = word_hashes(text)
    return [(hs[i] * 1000003 + hs[i + 1]) % NH for i in range(len(hs) - 1)]


def decode_table(tb):
    import numpy as np
    import base64
    if tb["hasher"] != HASHER:
        sys.exit(f"scoring table hasher {tb['hasher']} != this client's {HASHER}; update the client")
    raw = base64.b64decode(tb["values"])
    if hashlib.sha256(raw).hexdigest() != tb["sha256"]:
        sys.exit("scoring table checksum mismatch; download it again")
    t = np.frombuffer(raw, dtype="<f4").astype(np.float64)
    assert len(t) == tb["buckets"] == NH
    return t


def score_docs(table, docs):
    """Per document: the sum of table weights over its bigrams, and how many bigrams it has."""
    import numpy as np
    sums, cnts = [], []
    for d in docs:
        hs = np.array(word_hashes(d), dtype=np.int64)
        if len(hs) < 2:
            sums.append(0.0); cnts.append(0); continue
        b = (hs[:-1] * 1000003 + hs[1:]) % NH
        sums.append(float(table[b].sum())); cnts.append(len(b))
    return np.array(sums, dtype=np.float64), np.array(cnts, dtype=np.float64)


def score_pool(table, docs, keep_fraction, seed=0):
    """Mean table weight over each document's bigrams, then Gumbel-perturbed top-k.
    `docs` is any iterable of strings; memory = two floats per document."""
    import numpy as np
    sums, cnt = score_docs(table, docs)
    has = cnt > 0
    s_doc = np.full(len(cnt), -np.inf); s_doc[has] = sums[has] / cnt[has]
    eligible = np.flatnonzero(has)
    keep = max(1, int(round(keep_fraction * len(eligible))))
    rng = np.random.default_rng(9000 + seed)
    mean_len = float(cnt[has].mean())
    keys = s_doc[eligible] * mean_len + rng.gumbel(size=len(eligible))
    top = eligible[np.argpartition(-keys, keep - 1)[:keep]] if keep < len(eligible) else eligible
    return np.sort(top).tolist(), int(len(eligible)), int(len(cnt))


# ---------------- sharded selection ----------------
# A document's score needs only the document and the table, so shards are scored
# independently, anywhere. The cut is then made once over all of them: the same rule as
# score_pool (score scaled by the pool's mean length, plus seeded Gumbel noise, top k),
# with each shard's noise drawn from its own stream so that neither the order of the
# shards nor the number of workers can change the result. Memory at the cut is one
# shard's scores at a time, however large the pool.

_BINS = 1 << 20


def load_forecast_table(path):
    fc = json.load(open(path))
    if not fc.get("scoring_table"):
        sys.exit(f"forecast {fc.get('forecast_id')} carries no scoring table (verdict {fc.get('verdict')}): "
                 "if the verdict is DO-NOT-SELECT, train on a random keep list of the same size")
    return fc, decode_table(fc["scoring_table"])


def score_shard(forecast_path, shard_path, out_path, shard_id=None):
    """Score one shard and write its score file (12 bytes per document). No network."""
    import numpy as np
    fc, table = load_forecast_table(forecast_path)
    sums, cnt = score_docs(table, iter_docs(shard_path))
    meta = {"shard_id": shard_id or os.path.basename(os.path.normpath(shard_path)), "documents": int(len(cnt)),
            "forecast_id": fc["forecast_id"], "table_sha256": fc["scoring_table"]["sha256"], "hasher": HASHER, "client": CLIENT}
    os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
    tmp = out_path + ".tmp.npz"
    np.savez(tmp, sums=sums, cnt=cnt.astype(np.int32), meta=np.array(json.dumps(meta)))
    os.replace(tmp, out_path)                              # a half-written file is never mistaken for a finished one
    return meta


def _score_shard_job(job):
    return score_shard(*job)


def _score_files(paths):
    out = []
    for p in paths:
        if os.path.isdir(p):
            out += [os.path.join(p, f) for f in sorted(os.listdir(p)) if f.endswith(".npz") and not f.endswith(".tmp.npz")]
        else:
            out.append(p)
    return out


def merge_shards(fc, score_paths, keep_fraction, seed, out_dir):
    """The cut over every shard. Writes one keep file per shard into out_dir and returns
    the manifest (without a selection id; the caller reports it to the service)."""
    import numpy as np
    files = _score_files(score_paths)
    if not files:
        sys.exit("no score files found")
    shards = []
    for f in files:
        with np.load(f) as z:
            m = json.loads(str(z["meta"]))
            if m["table_sha256"] != fc["scoring_table"]["sha256"] or m["hasher"] != HASHER:
                sys.exit(f"{f} was scored with a different table or hasher than forecast {fc['forecast_id']}; score it again")
            cnt = z["cnt"]
            shards.append({**m, "file": f, "eligible": int((cnt > 0).sum()), "bigrams": int(cnt.sum(dtype=np.int64))})
    shards.sort(key=lambda m: m["shard_id"])
    ids = [m["shard_id"] for m in shards]
    if len(set(ids)) != len(ids):
        sys.exit("two score files carry the same shard id: " + next(i for i in ids if ids.count(i) > 1))
    n_all, n_el = sum(m["documents"] for m in shards), sum(m["eligible"] for m in shards)
    if n_el == 0:
        sys.exit("no document in any shard has two words or more")
    mean_len = sum(m["bigrams"] for m in shards) / n_el
    keep = max(1, int(round(keep_fraction * n_el)))

    def keys(m):   # (document indices in the shard, their keys); the same numbers every time it is called
        with np.load(m["file"]) as z:
            sums, cnt = z["sums"], z["cnt"].astype(np.float64)
        el = np.flatnonzero(cnt > 0)
        rng = np.random.default_rng([9000 + seed, zlib.crc32(m["shard_id"].encode()) & 0xFFFFFFFF])
        return el, sums[el] / cnt[el] * mean_len + rng.gumbel(size=len(el))

    if keep >= n_el:
        cut = None
    else:
        # the k-th largest key, exactly, without holding all keys: a fine histogram finds
        # the bin the cut falls in, then only that bin's keys are sorted
        lo, hi = np.inf, -np.inf
        for m in shards:
            k = keys(m)[1]
            if len(k):
                lo, hi = min(lo, float(k.min())), max(hi, float(k.max()))
        span = (hi - lo) or 1.0
        bin_of = lambda k: np.minimum(((k - lo) / span * _BINS).astype(np.int64), _BINS - 1)
        hist = np.zeros(_BINS, dtype=np.int64)
        for m in shards:
            hist += np.bincount(bin_of(keys(m)[1]), minlength=_BINS)
        above = np.cumsum(hist[::-1])[::-1]                 # keys in this bin or a higher one
        b = int(np.flatnonzero(above >= keep)[-1])
        need = keep - int(above[b + 1] if b + 1 < _BINS else 0)   # how many to take from bin b
        edge = np.concatenate([k[bin_of(k) == b] for k in (keys(m)[1] for m in shards)])
        thr = float(np.partition(edge, len(edge) - need)[len(edge) - need])
        ties = need - int((edge > thr).sum())                # keys equal to the cut still to be taken, in shard order
        cut = (b, thr)

    os.makedirs(out_dir, exist_ok=True)
    rows, kept_total, names = [], 0, set()
    for m in shards:
        el, k = keys(m)
        if cut is None:
            take = np.ones(len(el), dtype=bool)
        else:
            bi = bin_of(k)
            take = (bi > cut[0]) | ((bi == cut[0]) & (k > cut[1]))
            eq = np.flatnonzero((bi == cut[0]) & (k == cut[1]))[:ties]
            take[eq] = True; ties -= len(eq)
        idx = el[take].tolist()
        sha = hashlib.sha256(json.dumps(idx).encode()).hexdigest()
        name = re.sub(r"[^\w.-]", "_", m["shard_id"]) + ".keep.json"
        if name in names:
            sys.exit(f"two shard ids give the same file name: {name}")
        names.add(name)
        json.dump({"forecast_id": fc["forecast_id"], "shard_id": m["shard_id"], "documents": m["documents"],
                   "kept": len(idx), "keep_sha256": sha, "keep_indices": idx}, open(os.path.join(out_dir, name), "w"))
        rows.append({"shard_id": m["shard_id"], "documents": m["documents"], "eligible_documents": m["eligible"],
                     "kept": len(idx), "keep_sha256": sha, "file": name})
        kept_total += len(idx)
    assert kept_total == min(keep, n_el), (kept_total, keep, n_el)
    keep_sha = hashlib.sha256(json.dumps([[r["shard_id"], r["keep_sha256"]] for r in rows]).encode()).hexdigest()
    return {"forecast_id": fc["forecast_id"], "mode": "local-sharded", "keep_fraction": keep_fraction, "seed": seed,
            "hasher": HASHER, "table_sha256": fc["scoring_table"]["sha256"], "pool_documents": n_all,
            "eligible_documents": n_el, "kept": kept_total, "keep_sha256": keep_sha, "shards": rows}


def report_sharded(fc, man, out_dir):
    rep = call("selections", {"forecast_id": fc["forecast_id"], "keep_fraction": man["keep_fraction"],
                              "pool_total_documents": man["pool_documents"], "kept": man["kept"],
                              "table_sha256": man["table_sha256"], "keep_sha256": man["keep_sha256"],
                              "client": f"{CLIENT} sharded:{len(man['shards'])}"})
    man["selection_id"] = rep["selection_id"]
    json.dump(man, open(os.path.join(out_dir, "keep_manifest.json"), "w"), indent=1)
    print(json.dumps({**rep, "kept": man["kept"], "pool_documents": man["pool_documents"], "shards": len(man["shards"]),
                      "keep_files": f"written to {out_dir}"}, indent=1))


def selftest(verbose=True):
    v = call("hasher")
    if v["hasher"] != HASHER or v["buckets"] != NH:
        sys.exit(f"service hasher {v['hasher']}/{v['buckets']} != client {HASHER}/{NH}: update the client")
    for tv in v["test_vectors"]:
        assert word_hashes(tv["text"]) == tv["word_hashes"], tv
        assert buckets(tv["text"]) == tv["buckets"], tv
    if verbose:
        print(f"hasher {HASHER}: {len(v['test_vectors'])} vectors match the service")
    return True


# ---------------- commands ----------------

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    for name in ("forecast", "select"):
        s = sub.add_parser(name); s.add_argument("--target", required=True); s.add_argument("--pool", required=True)
        s.add_argument("--label"); s.add_argument("--keep", type=float, default=0.25); s.add_argument("--out")
        s.add_argument("--seed", type=int, default=0, help="sampling seed (recorded on the receipt)")
        s.add_argument("--pool-sample-words", type=int, default=5_000_000)
        s.add_argument("--target-sample-words", type=int, default=2_000_000)
        s.add_argument("--model-params", type=int, help="total parameters of the model you will train")
        s.add_argument("--active-params", type=int, help="mixture-of-experts: parameters active per token")
        s.add_argument("--language"); s.add_argument("--regime"); s.add_argument("--content", choices=("text", "code"))
        s.add_argument("--table", action="store_true", help="forecast: ask for the scoring table on SELECT")
    sl = sub.add_parser("select-local"); sl.add_argument("--forecast", required=True, help="forecast JSON saved with --out")
    sl.add_argument("--pool", required=True); sl.add_argument("--keep", type=float, default=0.25)
    sl.add_argument("--out", required=True); sl.add_argument("--seed", type=int, default=0)
    o = sub.add_parser("outcome"); o.add_argument("--forecast", required=True); o.add_argument("--selected", type=float)
    o.add_argument("--baseline", type=float); o.add_argument("--metric", default="held-out loss")
    o.add_argument("--acted", default="both"); o.add_argument("--notes")
    o.add_argument("--model-params", type=int, help="total parameters of the model you trained")
    o.add_argument("--active-params", type=int); o.add_argument("--train-tokens", type=int, help="tokens the run trained on")
    o.add_argument("--keep", type=float, help="fraction of the pool the run kept"); o.add_argument("--architecture")
    ss = sub.add_parser("score-shard", help="score one shard; needs no key and no network")
    ss.add_argument("--forecast", required=True); ss.add_argument("--shard", required=True); ss.add_argument("--out", required=True)
    ss.add_argument("--shard-id", help="name of this shard (default: the last part of its path)")
    sm = sub.add_parser("select-merge", help="make the cut over score files from score-shard")
    sm.add_argument("--scores", required=True, nargs="+", help="score files, or directories of them")
    sd = sub.add_parser("select-sharded", help="score every entry of --pool as a shard, in parallel, then make the cut")
    sd.add_argument("--pool", required=True); sd.add_argument("--workers", type=int, default=os.cpu_count() or 1)
    for s in (sm, sd):
        s.add_argument("--forecast", required=True); s.add_argument("--keep", type=float, default=0.25)
        s.add_argument("--seed", type=int, default=0); s.add_argument("--out", required=True, help="directory for the keep files")
    sub.add_parser("me"); sub.add_parser("selftest")
    a = ap.parse_args()
    if a.cmd == "score-shard":
        m = score_shard(a.forecast, a.shard, a.out, a.shard_id)
        print(json.dumps({**m, "scores": f"written to {a.out}"}, indent=1)); return
    if not KEY:
        sys.exit("set ECHOSPACE_API_KEY")
    if a.cmd in ("select-merge", "select-sharded"):
        fc, _ = load_forecast_table(a.forecast)
        selftest(verbose=False)
        if a.cmd == "select-sharded":
            if not os.path.isdir(a.pool):
                sys.exit("--pool must be a directory whose entries are the shards")
            names = sorted(n for n in os.listdir(a.pool) if not n.startswith("."))
            if not names:
                sys.exit(f"no shards under {a.pool}")
            scores = os.path.join(a.out, "scores")
            jobs = [(a.forecast, os.path.join(a.pool, n), os.path.join(scores, re.sub(r"[^\w.-]", "_", n) + ".npz"), n) for n in names]
            if a.workers > 1 and len(jobs) > 1:
                import multiprocessing
                with multiprocessing.get_context("spawn").Pool(min(a.workers, len(jobs))) as pool:
                    for i, m in enumerate(pool.imap_unordered(_score_shard_job, jobs), 1):
                        print(f"scored {m['shard_id']} ({i}/{len(jobs)})", file=sys.stderr)
            else:
                for j in jobs:
                    score_shard(*j)
            a.scores = [scores]
        report_sharded(fc, merge_shards(fc, a.scores, a.keep, a.seed, a.out), a.out)
        return
    if a.cmd == "me":
        print(json.dumps(call("me"), indent=1)); return
    if a.cmd == "selftest":
        selftest(); return
    if a.cmd == "outcome":
        scale = {k: v for k, v in {"model_params": a.model_params, "active_params": a.active_params,
                                   "train_tokens": a.train_tokens, "keep_fraction": a.keep,
                                   "architecture": a.architecture}.items() if v is not None}
        print(json.dumps(call("outcome", {"forecast_id": a.forecast, "acted": a.acted, "metric_name": a.metric,
                                          "selected_value": a.selected, "baseline_value": a.baseline, "notes": a.notes,
                                          **scale}), indent=1)); return
    if a.cmd == "select-local":
        fc, table = load_forecast_table(a.forecast)
        selftest(verbose=False)
        keep, n_el, n_all = score_pool(table, iter_docs(a.pool), a.keep, a.seed)
        keep_sha = hashlib.sha256(json.dumps(keep).encode()).hexdigest()
        rep = call("selections", {"forecast_id": fc["forecast_id"], "keep_fraction": a.keep, "pool_total_documents": n_all,
                                  "kept": len(keep), "table_sha256": fc["scoring_table"]["sha256"], "keep_sha256": keep_sha,
                                  "client": CLIENT})
        json.dump({"forecast_id": fc["forecast_id"], "selection_id": rep["selection_id"], "mode": "local",
                   "keep_fraction": a.keep, "pool_documents": n_all, "eligible_documents": n_el, "kept": len(keep),
                   "keep_sha256": keep_sha, "hasher": HASHER, "keep_indices": keep}, open(a.out, "w"))
        print(json.dumps({**rep, "kept": len(keep), "pool_documents": n_all, "keep_indices": f"written to {a.out}"}, indent=1))
        return
    # forecast / select: samples in, verdict out
    if a.cmd == "select":
        pool, n_pool = list(iter_docs(a.pool)), None    # server-side keep list needs the whole pool
        n_pool = len(pool)
    else:
        pool, n_pool = sample_docs(a.pool, a.pool_sample_words, a.seed)
    target, n_target = sample_docs(a.target, a.target_sample_words, a.seed)
    ctx = {k: v for k, v in {"model_params": a.model_params, "active_params": a.active_params, "keep_fraction": a.keep,
                             "language": a.language, "regime": a.regime, "content": a.content}.items() if v is not None}
    body = {"target": target, "pool": pool, "label": a.label, "context": ctx or None,
            "provenance": {"client": CLIENT, "pool_total_documents": n_pool, "target_total_documents": n_target,
                           "sample_seed": a.seed}}
    if a.cmd == "select":
        body["keep_fraction"] = a.keep
    else:
        body["table"] = a.table
    r = call(a.cmd, body)
    shown = dict(r)
    if a.out:
        json.dump(r, open(a.out, "w"))
        for big in ("keep_indices", "scoring_table"):
            if big in shown:
                shown[big] = f"written to {a.out}"
    elif "scoring_table" in shown and shown["scoring_table"]:
        shown["scoring_table"] = "(use --out to save it for select-local)"
    print(json.dumps(shown, indent=1))


if __name__ == "__main__":
    main()
