#!/usr/bin/env python3
import json, re, subprocess, os, sys

REPO = os.path.expanduser("~/social-autoposter")
LID = os.path.join(REPO, "scripts", "li_discovery.py")

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

def run(args):
    r = subprocess.run([sys.executable, LID] + args, capture_output=True, text=True)
    return (r.stdout or "").strip(), (r.stderr or "").strip(), r.returncode

# one context dump
ctx_out, ctx_err, rc = run(["context"])
ctx = json.loads(ctx_out) if ctx_out else {}
existing = set(ctx.get("existing_comment_ids") or [])
engaged_pairs = ctx.get("engaged_pairs") or []
posts = ctx.get("posts") or []

PARENT_RE = re.compile(r"urn:li:(?:activity|ugcPost|share):(\d+)")

# build parent_id -> post_id map
parent_to_post = {}
for p in posts:
    u = p.get("our_url") or ""
    m = PARENT_RE.search(u)
    if m:
        parent_to_post.setdefault(m.group(1), p["id"])

# build engaged set (author_lower, parent_id)
engaged_set = set()
for pair in engaged_pairs:
    if "|||" not in pair:
        continue
    author, url = pair.split("|||", 1)
    m = PARENT_RE.search(url)
    if m:
        engaged_set.add((author.strip().lower(), m.group(1)))

CU_RE = re.compile(r"\((?:activity|ugcPost|share):(\d+),(\d+)\)")

data = json.load(open("/tmp/li_notifs.json"))

counts = dict(scanned=len(data), new=0, already=0, engaged=0, excluded=0, own=0, no_urn=0)
new_items = []

def proj_for(snippet):
    s = (snippet or "").lower()
    # our niche is claude code / ai agents -> fazm flagship
    if any(k in s for k in ["claude code", "claude.md", "agent", "context window", "mcp", "subagent", "harness", "codex", "anthropic", "llm", "ai "]):
        return "fazm"
    return "general"

for it in data:
    cu = it.get("comment_urn")
    author = (it.get("author") or "").strip()
    if not cu:
        counts["no_urn"] += 1
        continue
    m = CU_RE.search(cu)
    if not m:
        counts["no_urn"] += 1
        continue
    parent_id = m.group(1)
    al = author.lower()
    # exclusion
    if al in OWN or author in ("unknown",):
        counts["own"] += 1
        continue
    if al in EXCLUDED_AUTHORS or any(x in al for x in EXCLUDED_AUTHORS):
        counts["excluded"] += 1
        continue
    if cu in existing:
        counts["already"] += 1
        continue
    if (al, parent_id) in engaged_set:
        counts["engaged"] += 1
        continue
    # find or create post
    post_id = parent_to_post.get(parent_id)
    if not post_id:
        proj = proj_for(it.get("snippet"))
        out, err, rc = run(["create-post", "--activity-id", parent_id, "--project", proj, "--author", author])
        post_id = out.strip().splitlines()[-1] if out.strip() else ""
        if not post_id:
            print(f"  [create-post FAILED parent={parent_id}] err={err}", file=sys.stderr)
            continue
        parent_to_post[parent_id] = post_id
    # insert reply
    out, err, rc = run([
        "insert-reply", "--post-id", str(post_id),
        "--comment-urn", cu, "--author", author,
        "--content", (it.get("snippet") or "")[:3000],
        "--href", it.get("href") or "",
    ])
    res = out.strip().splitlines()[-1] if out.strip() else ""
    if res == "duplicate":
        counts["already"] += 1
    elif res.startswith("gated"):
        counts["engaged"] += 1  # gated by blocklist/velocity, not actionable
        print(f"  [gated] {author} parent={parent_id} -> {res}", file=sys.stderr)
    elif res:
        counts["new"] += 1
        new_items.append((res, author, parent_id, cu))
        # mark as existing to dedup within this run
        existing.add(cu)
        engaged_set.add((al, parent_id))
    else:
        print(f"  [insert FAILED] {author} parent={parent_id} err={err}", file=sys.stderr)

print("\n=== NEW REPLIES INSERTED ===")
for rid, author, parent, cu in new_items:
    print(f"  reply_id={rid} author={author} parent={parent}")

print("\n=== SUMMARY ===")
print(f"New replies discovered:        {counts['new']}")
print(f"Already tracked:               {counts['already']}")
print(f"Author already engaged thread: {counts['engaged']}")
print(f"Excluded:                      {counts['excluded']}")
print(f"Own account:                   {counts['own']}")
print(f"No comment URN:                {counts['no_urn']}")
print(f"Total scanned:                 {counts['scanned']}")

excl_total = counts["excluded"] + counts["own"]
print(f"\nLINKEDIN_SCAN_SUMMARY: scanned={counts['scanned']} new={counts['new']} already={counts['already']} excluded={excl_total} unmatched={counts['no_urn']}")
