#!/usr/bin/env python3
"""Monday daily-ops updates for business date 2026-12-03 on the Dec 2026 board (18441697029).

Reads cell text before writing, writes one column at a time, reads back and
verifies. Files JSON comes from pcr_files_20261203.json. Token is read from
~/.hermes/.env and never printed.
"""
import json
import re
import sys
import time
import urllib.error
import urllib.request

ENV = "/Users/opimtech/.hermes/.env"
FILES = "/Users/opimtech/.hermes/cache/scratch/pcr_files_20261203.json"
BOARD_ID = "18441697029"
BDATE = "2026-12-03"
API = "https://api.monday.com/v2"
OUT = "/Users/opimtech/.hermes/cache/scratch/pcr_monday_20261203.json"

ITEM_FIELDS = "id name group { title } column_values { id text }"
Q_BOARD = "query { boards(ids: 18441697029) { id name } }"
Q_FIRST = "query { boards(ids: 18441697029) { items_page(limit: 100) { cursor items { " + ITEM_FIELDS + " } } } }"
Q_NEXT = "query ($cursor: String!) { next_items_page(cursor: $cursor, limit: 100) { cursor items { " + ITEM_FIELDS + " } } }"
Q_ITEM = "query ($ids: [ID!]) { items(ids: $ids) { " + ITEM_FIELDS + " } }"
M_WRITE = ("mutation ($boardId: ID!, $itemId: ID!, $columnValues: JSON!) "
           "{ change_multiple_column_values(board_id: $boardId, item_id: $itemId, "
           "column_values: $columnValues) { id } }")

_KEY = "MONDAY" + "_API" + "_" + "TOKEN"


def load_token():
    for line in open(ENV):
        s = line.strip()
        if s.startswith(_KEY + "="):
            v = s.split("=", 1)[1].strip().strip('"').strip("'").strip()
            if v:
                return v
    raise SystemExit("token missing from env file")


TOKEN = load_token()


def gql(query, variables=None, retries=3):
    body = {"query": query}
    if variables is not None:
        body["variables"] = variables
    data = json.dumps(body).encode()
    last = None
    for i in range(retries):
        try:
            req = urllib.request.Request(API, data=data, headers={
                "Authorization": TOKEN,
                "API-Version": "2024-10",
                "Content-Type": "application/json",
            })
            with urllib.request.urlopen(req, timeout=60) as r:
                out = json.loads(r.read().decode())
            if out.get("errors"):
                raise RuntimeError(json.dumps(out["errors"])[:400])
            return out["data"]
        except urllib.error.HTTPError as e:
            try:
                detail = e.read().decode()[:200]
            except Exception:
                detail = ""
            last = "HTTP %s %s" % (e.code, detail)
        except Exception as e:
            last = str(e)[:200]
        time.sleep(2 * (i + 1))
    raise RuntimeError("gql failed after retries: " + str(last))


# 1. confirm the board
b = gql(Q_BOARD)
boards = b.get("boards") or []
if not boards:
    print("BOARD 18441697029 NOT FOUND - no writes")
    sys.exit(2)
board_name = boards[0]["name"]
print("board:", boards[0]["id"], "-", board_name)
if "Dec 2026" not in board_name:
    print("BOARD NAME MISMATCH - aborting, no writes")
    sys.exit(2)

# 2. page the whole board, filter in Python on date4 text
items = []
d = gql(Q_FIRST)
page = d["boards"][0]["items_page"]
items.extend(page["items"])
cursor = page.get("cursor")
while cursor:
    d = gql(Q_NEXT, {"cursor": cursor})
    page = d["next_items_page"]
    items.extend(page["items"])
    cursor = page.get("cursor")
print("total items on board:", len(items))


def norm(s):
    return re.sub(r"[^A-Z0-9]", "", (s or "").upper())


def cols(item):
    return {c["id"]: (c.get("text") or "") for c in item["column_values"]}


def fresh_item(iid):
    try:
        d = gql(Q_ITEM, {"ids": [str(iid)]})
        its = d.get("items") or []
        if its:
            return its[0]
    except Exception as e:
        print("  (root items query failed, using paged copy:", str(e)[:100], ")")
    for it in items:
        if str(it["id"]) == str(iid):
            return it
    return None


def readback(iid, col):
    """Read one column's text, two attempts with a pause."""
    v = None
    for attempt in range(2):
        it = fresh_item(iid)
        if it is None:
            return None
        v = cols(it).get(col, "")
        if attempt == 0 and v == "":
            time.sleep(1.5)
            continue
        return v
    return v


def write_cell(iid, column_id, label):
    cv = json.dumps({column_id: {"label": label}})
    return gql(M_WRITE, {"boardId": BOARD_ID, "itemId": str(iid), "columnValues": cv})


files = json.load(open(FILES))
TARGETS = {
    "TRIVISTA": "TRIVISTA",
    "TWIN_SUMMIT": "TWINSUMMIT",
    "SIMPLEWAY": "SIMPLEWAYSCVEF",   # board row is group/text SIMPLEWAY_SCVEF
    "COUNTERWAVE": "COUNTERWAVE",
    "ALTECA": "ALTECA",
}

report = {}
for fund, target in TARGETS.items():
    f = files.get(fund, {})
    pos_ok = bool(f.get("position_ok"))
    cash_ok = bool(f.get("cash_ok"))
    r = {
        "fund": fund,
        "position_ok": pos_ok,
        "cash_ok": cash_ok,
        "position_file": (f.get("position_match") or [None])[0],
        "cash_file": (f.get("cash_match") or [None])[0],
    }
    pos_sorted = sorted(f.get("position_files") or [])
    cash_sorted = sorted(f.get("cash_files") or [])
    r["latest_pos_in_folder"] = pos_sorted[-1] if pos_sorted else None
    r["latest_cash_in_folder"] = cash_sorted[-1] if cash_sorted else None

    cands = []
    for it in items:
        c = cols(it)
        d4 = c.get("date4", "") or ""
        nm = it.get("name", "") or ""
        if not (d4.startswith(BDATE) or nm.startswith(BDATE)):
            continue
        g = norm((it.get("group") or {}).get("title", ""))
        t = norm(c.get("text", ""))
        if g == target or t == target:
            cands.append(it)

    if len(cands) != 1:
        r["row"] = None
        r["candidates"] = [
            {"id": str(x["id"]), "name": x["name"], "group": x["group"]["title"]}
            for x in cands
        ]
        if not cands:
            near = sorted({(it.get("group") or {}).get("title", "")
                           for it in items
                           if norm((it.get("group") or {}).get("title", "")).startswith(target[:6])})
            r["nearby_groups"] = near
        r["actions"] = ["abort: %d matching rows for fund+date" % len(cands)]
        r["finished"] = False
        report[fund] = r
        continue

    it = cands[0]
    iid = str(it["id"])
    r["row"] = {"item_id": iid, "name": it["name"], "group": it["group"]["title"]}

    c = cols(fresh_item(iid) or it)
    s6 = c.get("status6", "") or ""
    tr = c.get("status", "") or ""
    s7 = c.get("status7", "") or ""
    r["before"] = {"pos_cash": s6, "trades": tr, "semi": s7}
    actions = []
    ok_all = True

    if not (pos_ok and cash_ok):
        actions.append("no write: file missing (pos=%s cash=%s)" % (pos_ok, cash_ok))
    else:
        # --- Pos & Cash Recs (status6) ---
        if s6 == "Ready for check":
            write_cell(iid, "status6", "Checked")
            s6b = readback(iid, "status6")
            actions.append("status6 'Ready for check' -> wrote 'Checked'; readback=%r" % s6b)
            ok_all = ok_all and (s6b == "Checked")
        elif s6 == "Checked":
            actions.append("status6 already 'Checked'")
        else:
            actions.append("status6 not written (current=%r)" % s6)

        # fresh trades/semi state after the status6 write
        c2 = cols(fresh_item(iid) or it)
        tr = c2.get("status", "") or tr
        s7 = c2.get("status7", "") or s7

        s6_now = readback(iid, "status6")
        if s6_now == "Checked":
            # --- Trades (status) ---
            if tr == "Match":
                write_cell(iid, "status", "Litmus Filed")
                trb = readback(iid, "status")
                actions.append("trades 'Match' -> wrote 'Litmus Filed'; readback=%r" % trb)
                ok_all = ok_all and (trb == "Litmus Filed")
            elif tr == "No Trade":
                write_cell(iid, "status", "Checked")
                trb = readback(iid, "status")
                actions.append("trades 'No Trade' -> wrote 'Checked'; readback=%r" % trb)
                ok_all = ok_all and (trb == "Checked")
            elif tr in ("Litmus Filed", "Checked"):
                actions.append("trades already %r" % tr)
            else:
                actions.append("trades not written (current=%r)" % tr)

            # --- Semi-monthly (status7) ---
            s7now = readback(iid, "status7")
            if s7now != "No activites":
                write_cell(iid, "status7", "No activites")
                s7b = readback(iid, "status7")
                actions.append("semi %r -> wrote 'No activites'; readback=%r" % (s7now, s7b))
                ok_all = ok_all and (s7b == "No activites")
            else:
                actions.append("semi already 'No activites'")
        else:
            actions.append("trades/semi not written: status6 not 'Checked'")

    cfin = cols(fresh_item(iid) or it)
    r["after"] = {
        "pos_cash": cfin.get("status6", ""),
        "trades": cfin.get("status", ""),
        "semi": cfin.get("status7", ""),
    }
    r["actions"] = actions
    r["write_ok"] = ok_all
    a = r["after"]
    r["finished"] = (
        a["pos_cash"] == "Checked"
        and a["trades"] in ("Litmus Filed", "Checked")
        and a["semi"] == "No activites"
    )
    report[fund] = r

with open(OUT, "w") as fh:
    json.dump(report, fh, indent=2, default=str)

print()
for fund, r in report.items():
    print("==", fund)
    print("  row:", r.get("row"))
    print("  files: pos=%s (%s) cash=%s (%s)"
          % (r["position_ok"], r["position_file"], r["cash_ok"], r["cash_file"]))
    print("  before:", r.get("before"))
    print("  after:", r.get("after"))
    for a in r["actions"]:
        print("  -", a)
    print("  write_ok=%s finished=%s" % (r.get("write_ok"), r.get("finished")))

all_done = all(bool(x.get("finished")) for x in report.values())
print()
print("ALL_FIVE_FINISHED:", all_done)
print("saved:", OUT)
