"""Truth at a tick, the row-by-row comparison of a design's table with it, and the data checks.

The truth is the recorded tick itself (every event in the window, deleted ones included), after the row contract.
"""
from collections import Counter

from contract import TRACKED, aliases, check, normalize

CLASSES = ("stale", "missing", "old_key", "deleted_kept", "vanished")


class Truth:
    def __init__(self, tick_rows):
        self.live, self.deleted, self.alias_of = {}, set(), {}
        self.source_alias_pairs = set()
        for r in tick_rows:
            if r.get("status") == "deleted" and r.get("id"):
                self.deleted.add(r["id"])
            if check(r) or r["status"] == "deleted":
                continue
            self.live[r["id"]] = normalize(r)
        for i, r in self.live.items():
            for a in aliases(r):
                if a != i and a not in self.live:
                    self.alias_of.setdefault(a, i)
                elif a != i:
                    self.source_alias_pairs.add((i, a))  # the source itself lists a live event as another's alias

    def count(self):
        return len(self.live)


def compare(table, truth):
    """Error counts by class, duplicates, correct rows, and the ids behind each class (for examples)."""
    out = Counter()
    ids_by = {c: [] for c in CLASSES}
    present = Counter(r["id"] for r in table)
    seen = set()
    for r in table:
        i = r["id"]
        if i in truth.live:
            if i in seen:  # the same id a second time is a duplicate row
                out["repeat"] += 1
                out["duplicates"] += 1
                continue
            seen.add(i)
            t = truth.live[i]
            if any(r[f] != t[f] for f in TRACKED):
                out["stale"] += 1
                ids_by["stale"].append(i)
            else:
                out["correct"] += 1
        elif i in truth.alias_of:
            out["old_key"] += 1
            ids_by["old_key"].append(i)
            if truth.alias_of[i] in present:
                out["duplicates"] += 1
        elif i in truth.deleted:
            out["deleted_kept"] += 1
            ids_by["deleted_kept"].append(i)
        else:
            out["vanished"] += 1
            ids_by["vanished"].append(i)
    held = set(present)
    for i, t in truth.live.items():
        if i in held or any(a in held for a in aliases(t)):
            continue
        out["missing"] += 1
        ids_by["missing"].append(i)
    out["wrong"] = sum(out[c] for c in CLASSES) + out["repeat"]
    out["live"] = truth.count()
    out["table_rows"] = len(table)
    return dict(out), ids_by


def alias_pairs(table):
    idset = {r["id"] for r in table}
    return {(r["id"], a) for r in table for a in aliases(r) if a != r["id"] and a in idset}


def checks(table, source_count, now_ms, fresh_ms=30 * 60 * 1000):
    """The six data checks on a design's table. True means the check passed."""
    ids = [r["id"] for r in table]
    idset = set(ids)
    alias_hit = bool(alias_pairs(table))
    newest = max((r["updated"] for r in table), default=None)
    return {
        "unique_id": len(ids) == len(idset),
        "contract": all(check(dict(r)) is None for r in table),
        "no_deleted_status": all(r["status"] != "deleted" for r in table),
        "alias": not alias_hit,
        "count_reconciliation": len(table) == source_count,
        "freshness": newest is not None and now_ms - newest <= fresh_ms,
    }
