import json, sys, re, collections, itertools, statistics as st
from urllib.parse import urlparse
p1 = [json.loads(l) for l in open(sys.argv[1])]
p2 = [json.loads(l) for l in open(sys.argv[2])]
for r in p1: r["pass"] = 1
for r in p2: r["pass"] = 2
rows = p1 + p2
def norm(b):
    b = b.strip().strip('"\'').replace("™", "").replace("®", "")
    b = re.sub(r"\s*\(.*?\)\s*", " ", b)
    b = re.sub(r"\b(inc|ltd|llc|co)\.?$", "", b, flags=re.I).strip(" .,-")
    return b
def key(b): return re.sub(r"[^a-z0-9]", "", norm(b).lower())
disp = collections.defaultdict(collections.Counter)
for r in rows:
    for b in r["brands"]:
        if key(b): disp[key(b)][norm(b)] += 1
D = {k: c.most_common(1)[0][0] for k, c in disp.items()}
def ks(r): return list(dict.fromkeys(key(b) for b in r["brands"] if key(b)))
def jac(a, b): return len(a & b) / len(a | b) if a | b else 1.0
def host(u):
    h = urlparse(u).netloc.lower()
    return h[4:] if h.startswith("www.") else h
C = ("US", "UK", "IE")
base = [r for r in rows if r["run"] == 0]
cats = sorted({r["category"] for r in rows})
out = {"answers": len(rows), "base_answers": len(base),
       "usd_pass1_tokens_only": round(sum(r["usd"] for r in p1), 2), "usd_pass2": round(sum(r["usd"] for r in p2), 2),
       "pass2_searches_mean": round(st.mean(r["searches"] for r in p2), 2),
       "pass2_citations_mean": round(st.mean(len(r["citations"]) for r in p2), 1),
       "brands_per_answer_mean": round(st.mean(len(r["brands"]) for r in rows), 1), "categories": {}}
all_cross, all_first_same = [], 0
for cat in cats:
    cr = [r for r in base if r["category"] == cat]
    c = {"label": None, "countries": {}}
    for co in C:
        rs = [r for r in cr if r["country"] == co]
        cnt, first = collections.Counter(), collections.Counter()
        for r in rs:
            k = ks(r); cnt.update(k)
            if k: first[k[0]] += 1
        dom = collections.Counter()
        tld = collections.Counter()
        for r in rs:
            if r["pass"] != 2: continue
            hs = list(dict.fromkeys(host(u) for u in r["citations"]))
            dom.update(hs)
            for h in hs:
                tld["uk" if h.endswith(".uk") else "ie" if h.endswith(".ie") else "other"] += 1
        tot = sum(tld.values()) or 1
        c["countries"][co] = {"answers": len(rs), "distinct_brands": len(cnt),
            "top_brands_pct_of_answers": [(D[k], round(100 * v / len(rs))) for k, v in cnt.most_common(8)],
            "named_first": [(D[k], v) for k, v in first.most_common(4)],
            "top_cited_hosts_pass2": dom.most_common(8),
            "cited_host_share_pct": {k: round(100 * v / tot) for k, v in tld.items()}}
    # brands only ever seen in one country (pooled), among those in >=3 answers
    seen = {co: collections.Counter() for co in C}
    for r in cr: seen[r["country"]].update(ks(r))
    excl = {co: [(D[k], v) for k, v in seen[co].most_common() if v >= 3 and all(seen[o][k] == 0 for o in C if o != co)][:6] for co in C}
    c["country_only_brands"] = excl
    # country overlap per question, per pass, then mean
    jj = {("US", "UK"): [], ("US", "IE"): [], ("UK", "IE"): []}
    for ps in (1, 2):
        for qi in range(10):
            sets = {}
            for co in C:
                rr = [r for r in cr if r["pass"] == ps and r["qi"] == qi and r["country"] == co]
                if rr: sets[co] = set(ks(rr[0]))
            if len(sets) == 3:
                for a, b in jj: jj[(a, b)].append(jac(sets[a], sets[b]))
    c["country_jaccard"] = {f"{a}-{b}": round(st.mean(v), 2) for (a, b), v in jj.items()}
    # same question, same country, pass1 vs pass2
    cross, fs = [], 0
    for qi in range(10):
        for co in C:
            a = [r for r in cr if r["pass"] == 1 and r["qi"] == qi and r["country"] == co]
            b = [r for r in cr if r["pass"] == 2 and r["qi"] == qi and r["country"] == co]
            if a and b:
                ka, kb = ks(a[0]), ks(b[0])
                cross.append(jac(set(ka), set(kb)))
                if ka and kb and ka[0] == kb[0]: fs += 1
    c["same_country_pass_jaccard"] = round(st.mean(cross), 2)
    c["same_country_same_first_brand"] = f"{fs}/{len(cross)}"
    all_cross += cross; all_first_same += fs
    out["categories"][cat] = c
out["same_country_pass_jaccard_all"] = round(st.mean(all_cross), 2)
out["same_country_same_first_all"] = f"{all_first_same}/{len(all_cross)}"
# US repeats: 2 passes x (run 0..4) = 10 answers per question for qi 0,1
stab = []
for cat in cats:
    for qi in (0, 1):
        g = [r for r in rows if r["category"] == cat and r["qi"] == qi and r["country"] == "US"]
        sets = [set(ks(r)) for r in g]
        firsts = [ks(r)[0] if ks(r) else None for r in g]
        union = set().union(*sets); every = set.intersection(*sets)
        cnt = collections.Counter(k for s in sets for k in s)
        stab.append({"category": cat, "qi": qi, "answers": len(g), "question": g[0]["question"],
            "mean_pairwise_jaccard": round(st.mean(jac(a, b) for a, b in itertools.combinations(sets, 2)), 2),
            "brands_ever": len(union), "in_every_answer": [D[k] for k in every],
            "in_half_or_more": sum(1 for k, v in cnt.items() if v >= len(g) / 2),
            "most_common_first": collections.Counter(firsts).most_common(1)[0][1]})
out["us_repeats"] = stab
out["us_repeats_summary"] = {
    "questions": len(stab), "answers_each": stab[0]["answers"],
    "mean_pairwise_jaccard": round(st.mean(s["mean_pairwise_jaccard"] for s in stab), 2),
    "share_of_brands_in_every_answer": round(sum(len(s["in_every_answer"]) for s in stab) / sum(s["brands_ever"] for s in stab), 2),
    "mean_brands_ever": round(st.mean(s["brands_ever"] for s in stab), 1),
    "first_brand_modal_share": round(st.mean(s["most_common_first"] / s["answers"] for s in stab), 2)}
# global source types, pass 2
hosts = collections.Counter()
for r in p2: hosts.update(list(dict.fromkeys(host(u) for u in r["citations"])))
tot = sum(hosts.values())
def count(pred): return sum(v for h, v in hosts.items() if pred(h))
def share(pred): return round(100 * count(pred) / tot, 1)
REVIEW_SITES = ("g2.com", "capterra", "trustpilot", "getapp", "softwareadvice")
# "citations" counts each website once per answer; "raw_cited_urls" counts every URL as returned
out["sources_pass2"] = {"distinct_hosts": len(hosts), "citations": tot,
    "raw_cited_urls": sum(len(r["citations"]) for r in p2), "top": hosts.most_common(20),
    "reddit_count": count(lambda h: "reddit" in h), "youtube_count": count(lambda h: "youtube" in h),
    "wikipedia_count": count(lambda h: "wikipedia" in h),
    "review_sites_count": count(lambda h: any(x in h for x in REVIEW_SITES)),
    "reddit_pct": share(lambda h: "reddit" in h), "youtube_pct": share(lambda h: "youtube" in h),
    "wikipedia_pct": share(lambda h: "wikipedia" in h),
    "review_sites_pct": share(lambda h: any(x in h for x in REVIEW_SITES)),
    "answers_citing_reddit_pct": round(100 * sum(1 for r in p2 if any("reddit" in host(u) for u in r["citations"])) / len(p2))}
print(json.dumps(out, indent=1, ensure_ascii=False))
