#!/usr/bin/env python3
"""Re-verify '2 of 258' from raw E1 API files. Read only. Run: python3 -I verify_2of258.py
Uses only competitors_mentioned; never answer_verbatim."""
import json, glob, re, difflib, collections as C, itertools as I
D = "/home/user/mrcrtr1979-droid/namebeam-visibility-index/corpus/e1/NB-CZ-API_*"
ENG = ("openai", "anthropic", "gemini"); LO, HI = "2026-09-01", "2026-10-13"
SUF = {"llc","inc","pllc","pc","co","corp","ltd","llp"}
TRADE = {"plumbing","plumber","plumbers","roofing","roofer","roofers","law","firm","firms","dental","dentist","dentists","hvac","heating","cooling","air","conditioning","electric","electrical","electrician","contractors","contracting","contractor","services","service","group","associates","attorneys","attorney","lawyers","company","insurance","agency","marketing","digital","landscaping","lawn","care","pest","control","cleaning","painting","construction","remodeling","homecare","home","health","realty","real","estate","and","of"}
STATES = set("al ak az ar ca co ct de fl ga hi id il in ia ks ky la me md ma mi mn ms mo mt ne nv nh nj nm ny nc nd oh ok or pa ri sc sd tn tx ut vt va wa wv wi wy dc".split())
STATENAMES = {"alabama","alaska","arizona","arkansas","california","colorado","connecticut","delaware","florida","georgia","hawaii","idaho","illinois","indiana","iowa","kansas","kentucky","louisiana","maine","maryland","massachusetts","michigan","minnesota","mississippi","missouri","montana","nebraska","nevada","ohio","oklahoma","oregon","pennsylvania","tennessee","texas","utah","vermont","virginia","washington","wisconsin","wyoming"}
STOP_SUBSTR = ("yelp","angi","bbb","better business","google","thumbtack","homeadvisor","porch","houzz","nextdoor","reddit","facebook","linkedin","trustpilot","yellow pages","yellowpages","mapquest","bing","avvo","justia","findlaw","martindale","super lawyers","healthgrades","zocdoc","webmd","ratemds","vitals","clutch","upcity","g2","capterra","manta","designrush","sortlist","wikipedia","forbes","zillow","realtor.com","nolo","u.s. news","us news")
STOP_REG = ("state bar","bar association","board of","department of","dept of","commission","attorney general","city of","county of","state of","secretary of state","chamber of commerce","licens","ftc","federal trade","consumer financial","insurance commissioner","association")
GENERIC = {"research approaches","key things to evaluate","questions to ask","phone","specialty","certified","standard","irrigation","repairs","lawn","kansas city","northland","clay county","liberty"}
def stoplisted(n):
    l = n.lower()
    if l in GENERIC or len(l) < 3: return "generic"
    if any(k in l for k in STOP_REG): return "regulator"
    for k in STOP_SUBSTR:
        if re.search(r"(?<![a-z0-9])" + re.escape(k) + r"(?![a-z0-9])", l): return "directory"
    return None
def norm_a(s):  # as the story did
    s = re.sub(r"[^a-z0-9 ]", " ", s.lower().replace("&", " and "))
    s = re.sub(r"\b(llc|inc|co|corp|ltd|pllc|pc|llp|the)\b", " ", s)
    return " ".join(s.split())
def key_b(s, market):
    s = re.sub(r"[^a-z0-9 ]", " ", s.casefold().replace("&", " and "))
    t = [w for w in s.split() if w not in SUF]
    if t and t[0] == "the": t = t[1:]
    mk = {w for w in re.sub(r"[^a-z0-9 ]", " ", market.casefold()).split()} - {"and"}
    while t and (t[-1] in STATES or t[-1] in STATENAMES or t[-1] in mk): t.pop()
    t = [w for w in t if w not in TRADE]
    return " ".join(t)
def sim(a, b):
    ta, tb = sorted(set(a.split())), sorted(set(b.split()))
    return difflib.SequenceMatcher(None, " ".join(ta), " ".join(tb)).ratio()
raw = []
for f in glob.glob(D):
    if re.search(r"_r\d+\.json$", f): continue
    d = json.load(open(f))
    if not (LO <= d["date_utc"] <= HI) or d["engine"] not in ENG: continue
    raw.append(d)
g = C.defaultdict(dict)
for d in raw:
    if d["run_status"] == "OK":
        g[(d["date_utc"], d["business"], d["niche"], d["market"])][d["engine"]] = d
allq = {k: v for k, v in g.items()}
ok3 = {k: v for k, v in g.items() if len(v) == 3}
q258 = {k: v for k, v in ok3.items() if all(v[e]["competitors_mentioned"] for e in ENG)}
print("raw API rows in window, no _rN:", len(raw), "units with any OK:", len(g))
print("units all three OK:", len(ok3), " all three named >=1:", len(q258))
print("STOPLIST substrings (directories):", STOP_SUBSTR); print("STOPLIST regulators:", STOP_REG); print("GENERIC exact:", sorted(GENERIC))
print("TRADE words stripped (b,c):", sorted(TRADE)); print("legal suffixes:", sorted(SUF), "+ leading 'the', trailing state/city tokens (state codes/names and the question's market words)")
# market spread of each entity key across all questions (nationwide test)
spread = C.defaultdict(set)
for k, v in g.items():
    for e, d in v.items():
        for n in d["competitors_mentioned"]: spread[key_b(n, k[3])].add(k[3])
def prep(d, market, drop=True):
    out = {}
    for n in d["competitors_mentioned"]:
        if drop and stoplisted(n): continue
        out[n] = (norm_a(n), key_b(n, market))
    return out
def run(label, drop):
    res = {"a": [], "b": [], "c": []}; pr = {m: C.Counter() for m in "abc"}; n3 = {m: 0 for m in "abc"}
    for k, v in q258.items():
        P = {e: prep(v[e], k[3], drop) for e in ENG}
        for m in "abc":
            A = {e: [(n, x[0] if m == "a" else x[1]) for n, x in P[e].items() if (x[0] if m == "a" else x[1])] for e in ENG}
            def match(x, y): return x == y if m in "ab" else sim(x, y) >= 0.9
            for e1, e2 in I.combinations(ENG, 2):
                if any(match(x[1], y[1]) for x in A[e1] for y in A[e2]): pr[m][e1 + "+" + e2] += 1
            trip = [(x, y, z) for x in A["openai"] for y in A["anthropic"] if match(x[1], y[1]) for z in A["gemini"] if match(x[1], z[1]) and match(y[1], z[1])]
            if trip:
                n3[m] += 1; res[m].append((k, trip[0]))
    print("\n== %s ==" % label)
    for m, nm in (("a", "exact normalized"), ("b", "entity key"), ("c", "fuzzy>=0.9 on entity key")):
        print("matcher %s (%s): three-way %d of %d; pairwise (questions) %s" % (m, nm, n3[m], len(q258), dict(pr[m])))
        for k, (x, y, z) in res[m]:
            kk = key_b(x[0], k[3]); sp = len(spread.get(kk, ()))
            print("   shared in %s | %s | %s | %s :: openai=%r anthropic=%r gemini=%r | stoplist=%s | markets_seen_for_key=%d (%s)" % (k[0], k[1], k[2], k[3], x[0], y[0], z[0], stoplisted(x[0]), sp, "nationwide-like" if sp >= 5 else "local/niche"))
run("UNFILTERED (no stoplist; story basis)", False)
run("FILTERED (stoplist applied)", True)
