"""Reliable Robotics essay: re-read Reliable Robotics' News page at write time, without a browser.

reliable.co/news is a script-rendered shell; the items it shows come from the site's public Sanity CMS
(project 8fus8tk7, dataset production, document type newsItem). This queries that CMS directly, prints the
published count and the newest items, flags anything created or edited after the first
read of the page (2026-09-22 ~04:52Z), and saves the full response beside this file as newsroom_c6681.json.

No arguments. Read-only: two GET requests to the CMS's public query endpoint.
"""
import json, pathlib, urllib.parse, urllib.request, datetime

OUT = pathlib.Path(__file__).resolve().parent
API = "https://8fus8tk7.api.sanity.io/v2021-10-21/data/query/production"
FIRST_READ = "2026-09-22T04:52:00Z"
PUBLISHED = '_type=="newsItem" && !(_id in path("drafts.**"))'


def q(groq):
    url = API + "?" + urllib.parse.urlencode({"query": groq})
    req = urllib.request.Request(url, headers={"User-Agent": "newsroom_c6681"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode("utf-8"))["result"]


def main():
    items = q(f'*[{PUBLISHED}] | order(date desc)'
              '{date, author, title, href, summary, _createdAt, _updatedAt, "kind": type->title}')
    drafts = q('count(*[_type=="newsItem" && _id in path("drafts.**")])')
    kinds = {}
    for it in items:
        kinds[it.get("kind")] = kinds.get(it.get("kind"), 0) + 1
    since = [it for it in items if (it.get("_createdAt") or "") > FIRST_READ or (it.get("_updatedAt") or "") > FIRST_READ]
    after_june = [it for it in items if (it.get("date") or "") > "2026-06-17"]
    stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    print(f"read at {stamp}: {len(items)} published newsItem documents; by type {kinds}; drafts visible: {drafts}")
    print("newest six by the page's own date field:")
    for it in items[:6]:
        print(f"  {it['date']}  {it.get('author') or '-'}  |  {it['title']}")
    print(f"items dated after 2026-06-17: {len(after_june)} -> " + "; ".join(f"{i['date']} {i['title']}" for i in after_june))
    print(f"items created or edited after the first read ({FIRST_READ}): {len(since)}"
          + ("" if not since else " -> " + "; ".join(f"{i['date']} {i['title']} (updated {i['_updatedAt']})" for i in since)))
    (OUT / "newsroom_c6681.json").write_text(json.dumps(
        {"read_at": stamp, "endpoint": API, "published_count": len(items), "by_type": kinds,
         "drafts_visible": drafts, "items": items}, indent=1, ensure_ascii=False), encoding="utf-8")


if __name__ == "__main__":
    main()
