import json, os, urllib.request, urllib.error

BOARD_ID = "18441697029"
BDATE = "2026-12-03"
COLS = ("text", "status", "status6", "status7", "checker", "person0", "status00", "date4", "status3", "status4")

def token():
    for line in open(os.path.expanduser("~/.hermes/.env")):
        line = line.strip()
        if line.startswith("MONDAY_API_TOKEN"):
            return line.split("=", 1)[1].strip().strip('"').strip("'")
    raise SystemExit("NO_TOKEN")

T = token()

def gql(query, variables=None):
    body = {"query": query}
    if variables:
        body["variables"] = variables
    req = urllib.request.Request(
        "https://api.monday.com/v2",
        data=json.dumps(body).encode(),
        headers={"Authorization": T, "API-Version": "2024-10", "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=60) as r:
        res = json.load(r)
    if res.get("errors"):
        raise SystemExit("GRAPHQL_ERROR: " + json.dumps(res["errors"])[:500])
    return res

q1 = """query { boards(ids: %s) { id name items_page(limit: 100) { cursor items { id name group { title } column_values { id text value } } } } }""" % BOARD_ID
res = gql(q1)
b = res["data"]["boards"][0]
print("BOARD: %s | %s" % (b["id"], b["name"]))
items = b["items_page"]["items"]
cursor = b["items_page"]["cursor"]
while cursor:
    q2 = """query ($c: String!) { next_items_page(cursor: $c, limit: 100) { cursor items { id name group { title } column_values { id text value } } } }"""
    page = gql(q2, {"c": cursor})["data"]["next_items_page"]
    items += page["items"]
    cursor = page["cursor"]
print("TOTAL ITEMS:", len(items))

matches = [it for it in items if any(cv["id"] == "date4" and cv["text"] == BDATE for cv in it["column_values"])]
print("MATCHING %s: %d" % (BDATE, len(matches)))
out = []
for it in matches:
    row = {"item_id": it["id"], "name": it["name"], "group": it["group"]["title"], "cols": {}}
    for cv in it["column_values"]:
        row["cols"][cv["id"]] = cv["text"]
    out.append(row)
    print("ITEM %s | %s | group=%s" % (it["id"], it["name"], it["group"]["title"]))
    for cid in COLS:
        v = row["cols"].get(cid, "<absent>")
        print("    %-9s = %r" % (cid, v))

with open(os.path.expanduser("~/.hermes/cache/scratch/dec03_rows.json"), "w") as f:
    json.dump(out, f, indent=1)
print("WROTE dec03_rows.json")
