import json, re

items = json.load(open("/tmp/li_actionable.json"))
cids = set(l.strip() for l in open("/tmp/li_cids.txt") if l.strip())
pairs = set(l.strip() for l in open("/tmp/li_pairs.txt") if l.strip())
posts = []
for l in open("/tmp/li_posts.txt"):
    l=l.strip()
    if not l: continue
    pid, _, url = l.partition("|")
    posts.append((pid, url))

EXCLUDED = {"louis030195","louis3195"}
OWN = {"matthew diakonov","m13v"}

def parse_urn(urn):
    # urn:li:comment:(NS:PARENT,COMMENT)
    m = re.match(r"urn:li:comment:\((\w+):(\d+),(\d+)\)", urn or "")
    if not m: return (None,None,None)
    return m.group(1), m.group(2), m.group(3)

def find_post_id(parent_id):
    for pid, url in posts:
        if parent_id and parent_id in url:
            return pid
    return None

def author_engaged(author, parent_id):
    # any engaged pair with same author AND url containing parent_id
    al = author.strip().lower()
    for p in pairs:
        a, _, url = p.partition("|||")
        if a.strip().lower()==al and parent_id and parent_id in url:
            return True
    return False

seen_batch = set()
plan = []
counts = dict(new=0, already=0, engaged=0, excluded=0, own=0, nourn=0, dup_batch=0)

for it in items:
    urn = it.get("comment_urn")
    author = (it.get("author") or "").strip()
    ns, parent_id, comment_id = parse_urn(urn)
    rec = dict(it, ns=ns, parent_id=parent_id, comment_id=comment_id, decision=None, post_id=None)

    if not urn or not parent_id:
        rec["decision"]="skip:no_comment_urn"; counts["nourn"]+=1; plan.append(rec); continue
    if urn in seen_batch:
        rec["decision"]="skip:dup_in_batch"; counts["dup_batch"]+=1; plan.append(rec); continue
    seen_batch.add(urn)
    if urn in cids:
        rec["decision"]="skip:already_tracked"; counts["already"]+=1; plan.append(rec); continue
    al = author.lower()
    if al in OWN or any(al==e for e in EXCLUDED):
        rec["decision"]="skip:own_or_excluded"
        if al in OWN: counts["own"]+=1
        else: counts["excluded"]+=1
        plan.append(rec); continue
    if author_engaged(author, parent_id):
        rec["decision"]="skip:author_already_engaged"; counts["engaged"]+=1; plan.append(rec); continue
    pid = find_post_id(parent_id)
    rec["post_id"]=pid
    rec["decision"]="insert" if pid else "create_post+insert"
    counts["new"]+=1
    plan.append(rec)

json.dump(plan, open("/tmp/li_plan.json","w"), indent=2)
print("COUNTS:", counts)
print("TOTAL inspected:", len(items))
print()
for r in plan:
    if r["decision"].startswith("skip"): continue
    print(f"[{r['decision']}] {r['author']} | ns={r['ns']} parent={r['parent_id']} post_id={r['post_id']}")
    print(f"    urn: {r['comment_urn']}")
    print(f"    snip: {r['snippet'][:120]}")
