"""The row contract every design applies before loading, and the truth applies before scoring.

A record that fails goes to quarantine with its reason. Unknown property names are audited, never fatal.
"""
STATUSES = ("automatic", "reviewed", "deleted")
TRACKED = ("mag", "magType", "status", "time", "lon", "lat", "depth", "type")
COLUMNS = ("id", "ids", "status", "mag", "magType", "time", "updated", "type", "net", "lon", "lat", "depth")


def _num(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool)


def check(r):
    """Return None when the record passes, else the first reason it fails."""
    if not isinstance(r.get("id"), str) or not r["id"]:
        return "id missing"
    if not isinstance(r.get("time"), int) or isinstance(r.get("time"), bool):
        return "origin time missing or not an integer"
    if not isinstance(r.get("updated"), int) or isinstance(r.get("updated"), bool):
        return "updated time missing or not an integer"
    if r.get("status") not in STATUSES:
        return "status not in the accepted set"
    if not _num(r.get("lon")) or not _num(r.get("lat")):
        return "coordinates missing"
    if r.get("mag") is not None and not _num(r["mag"]):
        return "magnitude not a number"
    return None


def normalize(r):
    """The row as loaded: magnitude and depth as double, the aliases as a list without the empty ends."""
    out = {c: r.get(c) for c in COLUMNS}
    if out["mag"] is not None:
        out["mag"] = float(out["mag"])
    if out["depth"] is not None:
        out["depth"] = float(out["depth"])
    out["lon"], out["lat"] = float(out["lon"]), float(out["lat"])
    return out


def aliases(r):
    """Every id the event lists, its own included."""
    return [x for x in (r.get("ids") or "").split(",") if x]


def split(rows):
    """(passing rows normalized, [(record, reason)] failing, [(id, key)] unknown keys)."""
    good, bad, extra = [], [], []
    for r in rows:
        why = check(r)
        if why:
            bad.append((r, why))
            continue
        for k in (r.get("schema") or {}).get("extra", []):
            extra.append((r["id"], k))
        good.append(normalize(r))
    return good, bad, extra
