#!/usr/bin/env python3
import json, os, re, sys, time, urllib.request, urllib.error

SCRATCH = os.path.expanduser('~/.hermes/cache/scratch')
FILECHECK = os.path.join(SCRATCH, 'filecheck_20261203.txt')
RESULT_JSON = os.path.join(SCRATCH, 'monday_result_20261203.json')
BOARD_ID = '18441697029'
BDATE = '2026-12-03'
API = 'https://api.monday.com/v2'

key_name = 'MONDAY' + '_API' + '_TOKEN'
TOKEN = None
with open(os.path.expanduser('~/.hermes/.env')) as f:
    for line in f:
        ls = line.strip()
        if ls.startswith(key_name + '='):
            TOKEN = ls.split('=', 1)[1].strip().strip('"').strip("'")
if not TOKEN:
    print('FATAL: token not found in env file')
    sys.exit(1)
print('token: loaded')

FUNDS = [
    ('TRIVISTA', 'TRIVISTA'),
    ('TWIN_SUMMIT', 'TWIN_SUMMIT'),
    ('SIMPLEWAY', 'SIMPLEWAY_SCVEF'),
    ('COUNTERWAVE', 'COUNTERWAVE'),
    ('ALTECA', 'ALTECA'),
]

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

def gql(query, variables=None):
    data = json.dumps({'query': query, 'variables': variables or {}}).encode()
    last = None
    for i in range(3):
        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'):
                print('GQL_ERRORS:', json.dumps(out['errors'])[:400])
            return out
        except urllib.error.HTTPError as e:
            last = 'HTTP %s: %s' % (e.code, e.read().decode()[:200])
        except Exception as e:
            last = repr(e)[:200]
        print('gql attempt %d failed: %s' % (i + 1, last))
        time.sleep(3)
    print('FATAL: gql failed:', last)
    sys.exit(2)

def write_col(item_id, col_id, label):
    mq = ('mutation($iid: ID!, $bid: ID!, $cv: JSON!) { '
          'change_multiple_column_values(item_id: $iid, board_id: $bid, column_values: $cv) { id } }')
    vals = json.dumps({col_id: {'label': label}})
    res = gql(mq, {'iid': str(item_id), 'bid': BOARD_ID, 'cv': vals})
    ok = bool((res.get('data') or {}).get('change_multiple_column_values'))
    return ok

def read_texts(item_id):
    q = 'query($ids: [ID!]) { items(ids: $ids) { id column_values { id text } } }'
    res = gql(q, {'ids': [str(item_id)]})
    its = (res.get('data') or {}).get('items') or []
    if not its:
        return {}
    return {cv['id']: (cv.get('text') or '') for cv in its[0]['column_values']}

# ---- parse file check results ----
files = {}
for line in open(FILECHECK):
    line = line.strip()
    if not line.startswith('RESULT|'):
        continue
    parts = line.split('|')
    fund, folder, status = parts[1], parts[2], parts[3]
    detail = parts[5] if len(parts) > 5 else ''
    d = files.setdefault(fund, {})
    if folder == 'PositionRec':
        d['pos'] = {'found': status == 'FOUND', 'detail': detail, 'raw': status}
    else:
        d['cash'] = {'found': status == 'FOUND', 'detail': detail, 'raw': status}
print('filecheck:', {f: (v.get('pos', {}).get('raw'), v.get('cash', {}).get('raw')) for f, v in files.items()})

# ---- fetch board ----
q1 = ('query { boards(ids: [' + BOARD_ID + ']) { name items_page(limit: 100) { cursor '
      'items { id name group { title } column_values { id text value } } } } }')
res = gql(q1)
boards = (res.get('data') or {}).get('boards') or []
if not boards:
    print('FATAL: board %s not found: %s' % (BOARD_ID, json.dumps(res)[:300]))
    sys.exit(2)
board_name = boards[0]['name']
items = list(boards[0]['items_page']['items'])
cursor = boards[0]['items_page'].get('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 } } } }')
    res = gql(q2, {'c': cursor})
    ip = (res.get('data') or {}).get('next_items_page') or {}
    items.extend(ip.get('items') or [])
    cursor = ip.get('cursor')
print('board:', board_name, '| items scanned:', len(items))

def cvmap(item):
    return {cv['id']: cv for cv in item['column_values']}

date_items = []
for it in items:
    d4 = (cvmap(it).get('date4') or {}).get('text') or ''
    if d4.strip().startswith(BDATE):
        date_items.append(it)
print('items for %s: %d' % (BDATE, len(date_items)))
if date_items:
    print('column ids on first item:', sorted(cvmap(date_items[0]).keys()))

def find_fund(target_norm):
    hits = []
    for it in date_items:
        cvs = cvmap(it)
        g = norm((it.get('group') or {}).get('title'))
        t = norm((cvs.get('text') or {}).get('text'))
        if g == target_norm or t == target_norm:
            hits.append(it)
    return hits

report = []
all_finished = True
for fund, tname in FUNDS:
    fd = files.get(fund, {})
    pos_ok = fd.get('pos', {}).get('found', False)
    cash_ok = fd.get('cash', {}).get('found', False)
    pos_detail = fd.get('pos', {}).get('detail', '')
    cash_detail = fd.get('cash', {}).get('detail', '')
    entry = {'fund': fund, 'board_row': tname, 'pos_file': pos_detail, 'cash_file': cash_detail}
    hits = find_fund(norm(tname))
    if len(hits) != 1:
        entry['error'] = 'fund+date not unique (%d rows on board)' % len(hits)
        entry['finished'] = False
        report.append(entry)
        all_finished = False
        print('ROW %s ABORT: not unique (%d rows)' % (fund, len(hits)))
        continue
    item = hits[0]
    cvs = cvmap(item)
    pos_before = (cvs.get('status6') or {}).get('text') or ''
    trades_before = (cvs.get('status') or {}).get('text') or ''
    semi_before = (cvs.get('status7') or {}).get('text') or ''
    actions = []
    blocked = None
    pos_now, trades_now, semi_now = pos_before, trades_before, semi_before

    if not (pos_ok and cash_ok):
        miss = []
        if not pos_ok: miss.append('position')
        if not cash_ok: miss.append('cash')
        blocked = 'missing ' + '+'.join(miss) + ' file'
    else:
        if pos_before == 'Ready for check':
            ok = write_col(item['id'], 'status6', 'Checked')
            back = read_texts(item['id']).get('status6', '')
            actions.append('status6: Ready for check -> Checked (write %s, readback %r)' % ('ok' if ok else 'FAIL', back))
            pos_now = back
            if back != 'Checked':
                blocked = blocked or 'status6 write failed (readback %r)' % back
        elif pos_before == 'Checked':
            pos_now = 'Checked'
        else:
            pos_now = pos_before
            blocked = blocked or ('status6 is %r' % pos_before if pos_before else 'status6 blank')
        if pos_now == 'Checked':
            if trades_before in ('Match', 'No Trade'):
                new_label = 'Litmus Filed' if trades_before == 'Match' else 'Checked'
                ok = write_col(item['id'], 'status', new_label)
                back = read_texts(item['id']).get('status', '')
                actions.append('status: %s -> %s (write %s, readback %r)' % (trades_before, new_label, 'ok' if ok else 'FAIL', back))
                trades_now = back
                if back != new_label:
                    blocked = blocked or 'trades write failed (readback %r)' % back
            else:
                trades_now = trades_before
                if trades_before not in ('Litmus Filed', 'Checked'):
                    blocked = blocked or ('trades is %r' % trades_before if trades_before else 'trades blank')
            if semi_before != 'No activites':
                ok = write_col(item['id'], 'status7', 'No activites')
                back = read_texts(item['id']).get('status7', '')
                actions.append('status7: %r -> No activites (write %s, readback %r)' % (semi_before, 'ok' if ok else 'FAIL', back))
                semi_now = back
                if back != 'No activites':
                    blocked = blocked or 'semi write failed (readback %r)' % back
            else:
                semi_now = 'No activites'

    finished = (pos_now == 'Checked' and trades_now in ('Litmus Filed', 'Checked') and semi_now == 'No activites')
    if not finished:
        all_finished = False
    entry.update({
        'item_id': str(item['id']),
        'group': (item.get('group') or {}).get('title'),
        'poscash': '%r -> %r' % (pos_before, pos_now),
        'trades': '%r -> %r' % (trades_before, trades_now),
        'semi': '%r -> %r' % (semi_before, semi_now),
        'actions': actions,
        'blocked': blocked,
        'finished': finished,
    })
    report.append(entry)
    print('ROW %s item=%s group=%s' % (fund, item['id'], entry['group']))
    print('  pos&cash: %s | trades: %s | semi: %s' % (entry['poscash'], entry['trades'], entry['semi']))
    for a in actions:
        print('  action:', a)
    if blocked:
        print('  BLOCKED:', blocked)
    print('  finished:', finished)

summary = {'business_date': BDATE, 'board_id': BOARD_ID, 'board_name': board_name,
           'all_finished': all_finished, 'funds': report}
with open(RESULT_JSON, 'w') as f:
    json.dump(summary, f, indent=2)
print('SUMMARY all_finished=%s board=%s' % (all_finished, board_name))
