"""Server cards that list tools, compared with what their servers serve (HISTOR, 2026-11-28).

Input: the JSON lines export.sql prints (one comparable endpoint per line: the card's canonical tool
entries and the served ones, both as HISTOR stores them, mcp-tool-set-digest/1 canonical form).
Output: results/summary.json and results/endpoints.csv (no tool bodies).

    ssh ... psql ... < export.sql | gzip > pairs.jsonl.gz
    python3 compare.py pairs.jsonl.gz
"""
import collections, csv, gzip, json, re, sys
from pathlib import Path
from urllib.parse import urlsplit

OUT = Path(__file__).resolve().parent.parent / "results"
FRESH_SINCE = "2026-11-14"           # served list read OK in the last two weeks
ANNOTATION_KEYS = {"$schema", "additionalProperties", "title", "description", "examples", "default"}

def idx(entries):
    return {e.get("name"): e for e in (entries or []) if isinstance(e, dict)}

def ws(s):
    return re.sub(r"\s+", " ", s or "").strip()

def strip(node, keys):
    if isinstance(node, dict):
        return {k: strip(v, keys) for k, v in node.items() if k not in keys}
    if isinstance(node, list):
        return [strip(v, keys) for v in node]
    return node

def path_kind(url):
    url = url or ""
    for suffix, name in (("/.well-known/mcp/server-card.json", ".well-known/mcp/server-card.json"),
                         ("/.well-known/mcp.json", ".well-known/mcp.json"), ("/server-card", "<endpoint>/server-card")):
        if url.endswith(suffix):
            return name
    return "other (AI Catalog)"

def classify(r):
    """(class, depth): depth 'substantive' = names, description text or parameters; 'cosmetic' = whitespace,
    schema annotation keys, or an outputSchema only one side has."""
    if r["card"] == r["served"]:
        return "same", "same"
    c, s = idx(r["card_body"]), idx(r["served_body"])
    cn, sn = set(c), set(s)
    if cn != sn:
        if not cn & sn:
            return "names: no tool in common", "substantive"
        if cn < sn:
            return "names: the server serves tools the card does not list", "substantive"
        if cn > sn:
            return "names: the card lists tools the server does not serve", "substantive"
        return "names: some added, some missing", "substantive"
    desc = [n for n in cn if (c[n].get("description") or "") != (s[n].get("description") or "")]
    if any(ws(c[n].get("description")) != ws(s[n].get("description")) for n in desc):
        return "same names: description text differs", "substantive"
    inp = [n for n in cn if c[n].get("inputSchema") != s[n].get("inputSchema")]
    if any(strip(c[n].get("inputSchema"), ANNOTATION_KEYS) != strip(s[n].get("inputSchema"), ANNOTATION_KEYS) for n in inp):
        return "same names and descriptions: parameters differ", "substantive"
    if inp:
        return "input schemas differ only in annotation keys", "cosmetic"
    if desc:
        return "descriptions differ only in whitespace", "cosmetic"
    out = [n for n in cn if c[n].get("outputSchema") != s[n].get("outputSchema")]
    if out:
        if all("outputSchema" not in c[n] for n in out):
            return "only the server has output schemas", "cosmetic"
        return "output schemas differ", "cosmetic"
    return "other fields", "cosmetic"

def main(src):
    rows = [json.loads(line) for line in gzip.open(src, "rt") if line.strip()]
    host = lambda r: urlsplit(r["endpoint"]).hostname
    for r in rows:
        r["class"], r["depth"] = classify(r)
        r["fresh"] = (r["last_ok"] or "") >= FRESH_SINCE
        r["old_copy"] = r["depth"] != "same" and bool(r["card_ever_served"])
        r["path"] = path_kind(r["card_url"])

    def tally(sel):
        return {"endpoints": len(sel), "hosts": len({host(r) for r in sel})}
    diff = [r for r in rows if r["depth"] != "same"]
    sub = [r for r in rows if r["depth"] == "substantive"]
    fresh = [r for r in rows if r["fresh"]]
    summary = {
        "source": "HISTOR read-only Postgres (histor.modelmarket.dev), server_cards status 'declared' joined to targets with a served tool list",
        "exported_utc": "2026-11-28T17:59Z",
        "comparable": tally(rows),
        "differ": tally(diff),
        "differ_substantive": tally(sub),
        "differ_cosmetic_only": tally([r for r in rows if r["depth"] == "cosmetic"]),
        "fresh_served_reads_since_" + FRESH_SINCE: {**tally(fresh), "differ": len([r for r in fresh if r["depth"] != "same"]),
                                                   "differ_substantive": len([r for r in fresh if r["depth"] == "substantive"])},
        "classes": {k: {"endpoints": v, "hosts": len({host(r) for r in rows if r["class"] == k})}
                    for k, v in collections.Counter(r["class"] for r in rows).most_common()},
        "by_path": {p: {"endpoints": sum(1 for r in rows if r["path"] == p),
                        "differ": sum(1 for r in rows if r["path"] == p and r["depth"] != "same"),
                        "differ_substantive": sum(1 for r in rows if r["path"] == p and r["depth"] == "substantive")}
                    for p in sorted({r["path"] for r in rows})},
        "differing_card_was_served_earlier": tally([r for r in diff if r["old_copy"]]),
        "differing_where_current_served_set_is_newer_than_first_card_seen":
            len([r for r in diff if (r["unchanged_since"] or "") > (r["card_first_seen"] or "")]),
        "tool_count": dict(collections.Counter(
            "same count" if (r["served_n"] or 0) == (r["card_n"] or 0) else "server serves more" if (r["served_n"] or 0) > (r["card_n"] or 0)
            else "card lists more" for r in diff)),
        "largest_hosts": collections.Counter(host(r) for r in diff).most_common(5),
    }
    OUT.mkdir(exist_ok=True)
    (OUT / "summary.json").write_text(json.dumps(summary, indent=1) + "\n")
    cols = ["id", "name", "endpoint", "card_url", "path", "card", "card_n", "served", "served_n", "class", "depth",
            "old_copy", "card_first_seen", "card_ever_served", "card_last_served", "unchanged_since", "last_ok", "fresh", "delisted"]
    with open(OUT / "endpoints.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(cols)
        for r in sorted(rows, key=lambda r: (r["depth"], r["class"], r["endpoint"])):
            w.writerow([r.get(k) for k in cols])
    print(json.dumps(summary, indent=1))

if __name__ == "__main__":
    main(sys.argv[1])
