import json, re, urllib.parse

NOTIFS = "/tmp/li_notifs.json"
CID = "/Users/matthewdi/.claude/projects/-/f0a4ef0d-11f2-4618-85e2-bf62ad39cea2/tool-results/brzcccx3h.txt"
PAIRS = "/Users/matthewdi/.claude/projects/-/f0a4ef0d-11f2-4618-85e2-bf62ad39cea2/tool-results/bu0y0bphg.txt"
POSTS = "/Users/matthewdi/.claude/projects/-/f0a4ef0d-11f2-4618-85e2-bf62ad39cea2/tool-results/bnb5ginhc.txt"

def load_lines(p):
    out=[]
    for ln in open(p, encoding="utf-8", errors="replace"):
        ln=ln.rstrip("\n")
        # skip persisted-output wrapper lines
        if not ln or ln.startswith("<") or ln.startswith("Output too large") or ln.startswith("Preview") or ln.startswith("..."):
            continue
        out.append(ln)
    return out

comment_ids = set(load_lines(CID))
pairs = set(load_lines(PAIRS))
posts = load_lines(POSTS)

# activity number -> post id
post_by_act = {}
for ln in posts:
    if "|" not in ln: continue
    pid, url = ln.split("|",1)
    for m in re.findall(r"urn:li:(?:activity|share|ugcPost):(\d+)", url):
        post_by_act[m]=pid

# config projects search_topics
cfg = json.load(open("/Users/matthewdi/social-autoposter/config.json"))
projtopics = []
for pr in cfg.get("projects",[]):
    projtopics.append((pr["name"], [t.lower() for t in pr.get("search_topics",[])]))

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

def match_project(snippet):
    s = snippet.lower()
    best=None; bestscore=0
    for name, topics in projtopics:
        score=0
        for t in topics:
            if t and t in s:
                score+=1
        if score>bestscore:
            bestscore=score; best=name
    return best or "S4L"

data = json.load(open(NOTIFS))
decisions=[]
for d in data:
    href = d["href"]
    dec = urllib.parse.unquote(href)
    m = re.search(r"urn:li:activity:(\d+)", dec)
    activity_id = m.group(1) if m else None
    comment_urn = d["comment_urn"]
    author = d["author"]
    a_low = author.lower().strip()
    rec = dict(author=author, activity_id=activity_id, comment_urn=comment_urn,
               snippet=d["snippet"], href=href, type=d["type"])
    if not comment_urn or not activity_id:
        rec["decision"]="no_comment_urn"; decisions.append(rec); continue
    if a_low in OWN:
        rec["decision"]="own_account"; decisions.append(rec); continue
    if a_low in EXCLUDED or any(x in a_low for x in EXCLUDED):
        rec["decision"]="excluded_author"; decisions.append(rec); continue
    if comment_urn in comment_ids:
        rec["decision"]="already_tracked"; decisions.append(rec); continue
    our_url = "https://www.linkedin.com/feed/update/urn:li:activity:%s/" % activity_id
    apk = author + "|||" + our_url
    if apk in pairs:
        rec["decision"]="author_already_engaged"; decisions.append(rec); continue
    # match post
    pid = post_by_act.get(activity_id)
    rec["post_id"]=pid
    rec["project"]=match_project(d["snippet"])
    rec["decision"]="INSERT"
    decisions.append(rec)

json.dump(decisions, open("/tmp/li_decisions.json","w"))
# summary
from collections import Counter
c=Counter(r["decision"] for r in decisions)
print("TOTAL", len(decisions))
for k,v in c.items(): print(k,v)
print("---INSERTS---")
for i,r in enumerate(decisions):
    if r["decision"]=="INSERT":
        print(i, r["author"], "| act", r["activity_id"], "| post", r.get("post_id"), "| proj", r["project"])
