"""s3c census instrument (LOCAL, UNCOMMITTED; stage-3 served census 2026-11-12).

Loaded by zz_s3c_census.pth in every python process of the container, active only when
S3C_OUT is set. Wraps the stock exllamav3_ext entry points (exl3_gemm, exl3_gemv, and for
the record exl3_mgemm / exl3_moe) once the extension module is imported, and counts every
call by (kernel, phase, step class, capturing, A rows x K, trellis shape, caller). Python-side
only: a CUDA-graph replay never reaches python, so a captured cell counts its CAPTURES (the
boot sweep), exactly as stock_gemm_guard does. Also snapshots stock_gemm_guard's own
STOCK_GEMM_CELLS / RECONSTRUCT_LEG_CELLS. Dumps JSON to $S3C_OUT/cells.<pid>.json.
"""
import json
import os
import sys
import threading
import time

OUT = os.environ.get("S3C_OUT")
_CELLS = {}
_LOCK = threading.Lock()
_PHASE = ["boot"]
_PATCHED = set()
_NAMES = ("exl3_gemm", "exl3_gemv", "exl3_mgemm", "exl3_moe")


def _caller():
    f = sys._getframe(2)
    out = []
    while f is not None and len(out) < 3:
        mod = f.f_globals.get("__name__", "?")
        if mod.startswith("arbi_serve") and not mod.endswith("stock_gemm"):
            out.append(f"{mod.rsplit('.', 1)[-1]}:{f.f_code.co_name}")
        f = f.f_back
    return ">".join(out)


def _step_class():
    co = sys.modules.get("arbi_serve.weight_quant.exl3.custom_op")
    if co is None:
        return "?"
    try:
        return co._seen_class()
    except Exception:  # noqa: BLE001
        return "?"


def _capturing():
    try:
        import torch

        return bool(torch.cuda.is_current_stream_capturing())
    except Exception:  # noqa: BLE001
        return False


def _shape(t):
    try:
        return "x".join(str(int(s)) for s in t.shape)
    except Exception:  # noqa: BLE001
        return "-"


def _wrap(name, fn):
    def w(*args, **kw):
        try:
            a = args[0]
            rows = int(a.numel() // a.shape[-1]) if hasattr(a, "shape") and a.dim() else -1
            kin = int(a.shape[-1]) if hasattr(a, "shape") and a.dim() else -1
            b = _shape(args[1]) if len(args) > 1 else "-"
            c = _shape(args[2]) if len(args) > 2 else "-"
            key = (name, _PHASE[0], _step_class(), _capturing(), rows, kin, b, c, _caller())
            with _LOCK:
                _CELLS[key] = _CELLS.get(key, 0) + 1
        except Exception as e:  # noqa: BLE001 -- the census never breaks a launch
            with _LOCK:
                k = (name, "ERR", repr(e)[:80], False, 0, 0, "", "", "")
                _CELLS[k] = _CELLS.get(k, 0) + 1
        return fn(*args, **kw)

    w.__s3c__ = True
    return w


def _try_patch():
    for modname in ("exllamav3_ext", "exllamav3.ext"):
        m = sys.modules.get(modname)
        if m is None:
            continue
        ext = getattr(m, "exllamav3_ext", m)
        for n in _NAMES:
            fn = getattr(ext, n, None)
            if fn is not None and not getattr(fn, "__s3c__", False):
                setattr(ext, n, _wrap(n, fn))
                _PATCHED.add(f"{getattr(ext, '__name__', '?')}.{n}")


def _guard_snapshot():
    g = sys.modules.get("arbi_serve.weight_quant.exl3.stock_gemm_guard")
    if g is None:
        return {}
    try:
        return {
            "STOCK_GEMM_CELLS": [[list(k), v] for k, v in g.STOCK_GEMM_CELLS.items()],
            "RECONSTRUCT_LEG_CELLS": [[list(k), v] for k, v in g.RECONSTRUCT_LEG_CELLS.items()],
            "counters": {
                c.name: c.fired
                for c in (g.STOCK_GEMM_STEP, g.STOCK_GEMM_STEP_CAPTURED, g.STOCK_GEMM_OTHER,
                          g.RECONSTRUCT_LEG_PREFILL, g.RECONSTRUCT_LEG_OTHER)
            },
        }
    except Exception as e:  # noqa: BLE001
        return {"error": repr(e)}


def _dump():
    with _LOCK:
        cells = [[list(k), v] for k, v in _CELLS.items()]
    doc = {"pid": os.getpid(), "argv": sys.argv[:4], "t": time.time(), "patched": sorted(_PATCHED),
           "phase": _PHASE[0], "cells": cells, "guard": _guard_snapshot()}
    p = os.path.join(OUT, f"cells.{os.getpid()}.json")
    tmp = p + ".tmp"
    with open(tmp, "w") as f:
        json.dump(doc, f)
    os.replace(tmp, p)


def _loop():
    last = 0.0
    while True:
        try:
            _try_patch()
            try:
                with open(os.path.join(OUT, "phase")) as f:
                    ph = f.read().strip() or "boot"
            except OSError:
                ph = "boot"
            _PHASE[0] = ph
            now = time.time()
            if (_CELLS or _PATCHED) and now - last > 10:
                _dump()
                last = now
        except Exception:  # noqa: BLE001
            pass
        time.sleep(0.05 if not _PATCHED else 0.5)


if OUT and os.path.isdir(OUT):
    threading.Thread(target=_loop, name="s3c-census", daemon=True).start()
