"""Turns results.jsonl (November run) into summary.json and results.csv.
Uses the first 100 serving domains in sample order (the last batch overshoots).

Two groups of checks:
  problems   something a launch checklist should have caught: noindex on the homepage, robots.txt
             blocking Googlebot from everything, plain http that stays on http, HTTP 200 for a made-up URL,
             no working favicon, a missing or default <title>, a sitemap listed in robots.txt that does
             not load, a canonical pointing at another site or at http:// from an https page
  look       worth a look, not an error on its own: no robots.txt, no Sitemap line, no sitemap found in
             the checked places, no canonical, a canonical on another site (I read each one; a mirror
             domain pointing to its main domain counts as deliberate), links to hosts that look like staging or dev
october_definition repeats the October headline (seven checks, including a missing Sitemap line)
so both runs can be compared on the same rule.
"""
import csv, json, sys
from measure import DEFAULT_TITLES

rows = [json.loads(l) for l in open("results.jsonl")]
for r in rows:
    if r.get("serving"):
        t = r["title"] or ""
        r["title_default"] = bool(t) and (t.lower() in DEFAULT_TITLES or "just another wordpress site" in t.lower())
# manual review (review.json, written by hand after reading every match):
# {"<domain>": {"staging_confirmed": bool, "canonical_intended": bool, "note": "..."}}
# unreviewed staging matches count as look-only; unreviewed cross-site canonicals count as problems
try:
    REVIEW = json.load(open("review.json"))
except FileNotFoundError:
    REVIEW = {}

tried = sorted(rows, key=lambda r: r["sample_index"])
serving = [r for r in tried if r["serving"]][:100]
cut = serving[-1]["sample_index"]
tried_upto = [r for r in tried if r["sample_index"] <= cut]


def n(f):
    return sum(1 for r in serving if f(r))


PROBLEMS = {
    "noindex_home": lambda r: bool(r["noindex_meta"] or r["noindex_header"]),
    "robots_blocks_googlebot": lambda r: r["robots_disallow_all"],
    "http_stays_http": lambda r: r["http_stays_http"],
    "soft404": lambda r: r["soft404"],
    "favicon_missing": lambda r: not r["favicon_ok"],
    "title_missing_or_default": lambda r: r["title_missing"] or r["title_default"],
    "sitemap_listed_but_broken": lambda r: r["sitemap_listed_but_broken"],
    "canonical_other_site_unexplained": lambda r: r.get("canonical_other_host", False)
        and not REVIEW.get(r["domain"], {}).get("canonical_intended", False),
    "canonical_http_on_https": lambda r: r.get("canonical_http", False),
}
LOOK = {
    "robots_txt_missing": lambda r: r["robots_code"] != 200,
    "sitemap_not_in_robots": lambda r: not r["sitemap_in_robots"],
    "sitemap_not_found": lambda r: not r["sitemap_ok"],
    "canonical_missing": lambda r: not r.get("canonical"),
    "canonical_other_site": lambda r: r.get("canonical_other_host", False),
    "canonical_www_mismatch": lambda r: r.get("canonical_www_mismatch", False),
    "staging_like_links": lambda r: bool(r.get("staging_hosts")),
    "staging_links_confirmed": lambda r: bool(r.get("staging_hosts")) and REVIEW.get(r["domain"], {}).get("staging_confirmed", False),
}
OCT = [lambda r: bool(r["noindex_meta"] or r["noindex_header"]), lambda r: r["robots_disallow_all"],
       lambda r: not r["sitemap_in_robots"], lambda r: r["soft404"], lambda r: not r["favicon_ok"],
       lambda r: r["title_missing"] or r["title_default"], lambda r: r["http_stays_http"]]

per_site = [sum(bool(f(r)) for f in PROBLEMS.values()) for r in serving]
oct_per_site = [sum(bool(f(r)) for f in OCT) for r in serving]
summary = {
    "run": "November 2026",
    "list": "Tranco 94GG2, ranks 1-100000, random.Random(20261006)",
    "user_agent": "CometWebResearch/1.0 (+https://cometweb.io)",
    "domains_tried": len(tried_upto), "serving": len(serving),
    "not_serving_reasons": {w: sum(1 for r in tried_upto if not r["serving"] and r.get("why") == w)
                            for w in sorted({r.get("why") for r in tried_upto if not r["serving"]})},
    "problems": {k: n(f) for k, f in PROBLEMS.items()},
    "look": {k: n(f) for k, f in LOOK.items()},
    "detail": {
        "soft404_redirect_to_home": n(lambda r: r["probe_to_home"]),
        "http_unreachable": n(lambda r: r["http_unreachable"]),
        "robots_star_disallow_all_only": n(lambda r: r.get("robots_star_disallow_all") and not r["robots_disallow_all"]),
        "sitemap_found_but_not_in_robots": n(lambda r: r["sitemap_ok"] and not r["sitemap_in_robots"]),
        "title_missing": n(lambda r: r["title_missing"]),
        "title_default": n(lambda r: r["title_default"]),
    },
    "sites_with_a_problem": sum(1 for x in per_site if x),
    "problems_per_site": {str(k): per_site.count(k) for k in range(0, 10) if per_site.count(k)},
    "october_definition": {"sites_flagged": sum(1 for x in oct_per_site if x),
                           "flags_per_site": {str(k): oct_per_site.count(k) for k in range(0, 8) if oct_per_site.count(k)}},
    "default_titles_seen": [r["title"] for r in serving if r["title_default"]],
    "noindex_sites": [r["domain"] for r in serving if r["noindex_meta"] or r["noindex_header"]],
    "disallow_all_sites": [r["domain"] for r in serving if r["robots_disallow_all"]],
}
json.dump(summary, open("summary.json", "w"), indent=1)
cols = ["domain", "home_final", "noindex_meta", "noindex_header", "robots_code", "robots_disallow_all",
        "robots_star_disallow_all", "sitemap_in_robots", "sitemap_ok", "sitemap_url", "probe_code", "soft404",
        "probe_to_home", "favicon_ok", "title", "title_missing", "title_default", "http_code", "http_final",
        "http_stays_http", "canonical", "canonical_other_host", "canonical_www_mismatch", "canonical_http",
        "staging_hosts"]
with open("results.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(cols)
    for r in serving:
        w.writerow([("; ".join(r.get(c) or []) if c == "staging_hosts" else r.get(c)) for c in cols])
if "-q" not in sys.argv:
    print(json.dumps(summary, indent=1))
