"""The single place where a Bluesky postView is turned into the fields we store and the one-line text the judge reads — so search, the firehose and the backfill all surface the same metadata (timestamp, engagement counts, and any images/video/link/quote). `extract` is the canonical normalizer: every post that enters the pool goes through it, so the stored shape is stable no matter where it was found. """ import re def _fmt_date(iso: str) -> str: """'2026-07-20T14:03:22.123Z' -> '2026-07-20 14:03' (UTC, to the minute).""" if not iso: return "?" return iso.replace("T", " ")[:16] def _domain(url: str) -> str: return re.sub(r"^https?://(www\.)?", "", url).split("/")[0] if url else "" def _media_markers(embed: dict) -> list[str]: """One or more short tags describing an embed's media, e.g. ['images:2'].""" etype = embed.get("$type", "") if "embed.images" in etype: imgs = embed.get("images", []) alt = sum(1 for i in imgs if (i.get("alt") or "").strip()) tag = f"images:{len(imgs)}" return [tag + f" ({alt} w/alt)" if alt else tag] if "embed.video" in etype: return ["video"] if "embed.external" in etype: dom = _domain((embed.get("external") or {}).get("uri", "")) return [f"link:{dom}" if dom else "link"] return [] def summarize_embed(post: dict) -> list[str]: """Turn a postView's hydrated embed into tags: images / video / link / quote.""" embed = post.get("embed") or {} etype = embed.get("$type", "") if "recordWithMedia" in etype: return _media_markers(embed.get("media") or {}) + ["quote"] if "embed.record" in etype: # a bare quote post return ["quote"] return _media_markers(embed) def extract(post: dict) -> dict: """Normalize a raw Bluesky postView into the fields we print/store.""" author = post.get("author") or {} record = post.get("record") or {} return { "uri": post["uri"], "did": author.get("did", ""), "handle": author.get("handle", ""), "displayName": author.get("displayName", ""), "text": record.get("text", ""), "createdAt": record.get("createdAt", ""), "replyTo": (record.get("reply") or {}).get("parent", {}).get("uri", ""), "likeCount": post.get("likeCount", 0), "replyCount": post.get("replyCount", 0), "repostCount": post.get("repostCount", 0), "media": summarize_embed(post), } def format_line(index: int, p: dict, prefix: str = "") -> str: """The one canonical post line the judge reads. `p` is an extract() dict. `[N] @handle L likes / R replies / P reposts [media] at://uri — preview` """ preview = " ".join(p["text"].split())[:140] counts = f"{p['likeCount']} likes / {p['replyCount']} replies / {p['repostCount']} reposts" media = f" [{', '.join(p['media'])}]" if p["media"] else "" return ( f"{prefix}[{index}] @{p['handle']} {_fmt_date(p['createdAt'])} " f"{counts}{media} {p['uri']} — {preview}" )