import json, os, urllib.request

TOKEN = os.environ['MONDAY_API_TOKEN']
BOARD = 18441697029

def gql(query, variables=None):
    payload = {"query": query}
    if variables is not None:
        payload["variables"] = variables
    req = urllib.request.Request(
        "https://api.monday.com/v2",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": TOKEN,
            "API-Version": "2024-10",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.load(r)

MUT = 'mutation ($b: ID!, $i: ID!, $c: JSON!) { change_multiple_column_values(board_id: $b, item_id: $i, column_values: $c) { id } }'
READ = 'query ($i: [ID!]) { items(ids: $i) { id name column_values { id text } } }'

def read_cells(item_id):
    d = gql(READ, {"i": [str(item_id)]})
    items = (d.get('data') or {}).get('items') or []
    if not items:
        return {}
    return {c['id']: c.get('text') for c in items[0]['column_values']}

def write_col(item_id, col, label):
    cvals = json.dumps({col: {"label": label}})
    d = gql(MUT, {"b": str(BOARD), "i": str(item_id), "c": cvals})
    if d.get('errors'):
        return False, json.dumps(d['errors'])
    return True, ''

FUNDS = [
    ("COUNTERWAVE", 13658086132),
    ("SIMPLEWAY_SCVEF", 13658105701),
]

for fund, item in FUNDS:
    cells = read_cells(item)
    cur = cells.get('status6')
    print(f"{fund}: status6 before={cur!r}")
    if cur == 'Checked':
        print(f"{fund}: status6 already Checked, skip")
        ok6 = True
    elif cur == 'Ready for check':
        ok, err = write_col(item, 'status6', 'Checked')
        after = read_cells(item).get('status6')
        print(f"{fund}: wrote status6 -> {after!r} (ok={ok} err={err})")
        ok6 = (after == 'Checked')
    else:
        print(f"{fund}: status6 is {cur!r}, not 'Ready for check' - no write")
        ok6 = False
    if not ok6:
        print(f"{fund}: Pos&Cash not Checked - skip Trades and Semi")
        continue
    cells = read_cells(item)
    cur = cells.get('status')
    print(f"{fund}: Trades before={cur!r}")
    if cur in ('Litmus Filed', 'Checked'):
        print(f"{fund}: Trades already {cur!r}, skip")
    elif cur in ('Match', 'No Trade'):
        label = 'Litmus Filed' if cur == 'Match' else 'Checked'
        ok, err = write_col(item, 'status', label)
        after = read_cells(item).get('status')
        print(f"{fund}: wrote Trades -> {after!r} (ok={ok} err={err})")
    else:
        print(f"{fund}: Trades is {cur!r}, unexpected - no write")
    cells = read_cells(item)
    cur = cells.get('status7')
    print(f"{fund}: Semi before={cur!r}")
    if cur == 'No activites':
        print(f"{fund}: Semi already 'No activites', skip")
    else:
        ok, err = write_col(item, 'status7', 'No activites')
        after = read_cells(item).get('status7')
        print(f"{fund}: wrote Semi -> {after!r} (ok={ok} err={err})")
    cells = read_cells(item)
    print(f"{fund} FINAL: status6={cells.get('status6')!r} status={cells.get('status')!r} status7={cells.get('status7')!r}")
