File size: 28,110 Bytes
d45a493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
"""
Reward Script: X2 — Won deal to invoice to notification
Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py
Variant: eval
Mocks: hubspot_mock,quickbooks_mock,gmail_mock
"""
import copy
import re
import sys

import requests


try:
    with open('/tmp/task_web_sid', encoding='utf-8') as f:
        sid = f.read().strip()
    if not sid:
        raise ValueError('sid is empty')
except Exception as e:
    print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
    print('REWARD: 0.0')
    sys.exit(0)


APP_URLS = {'hubspot': 'http://28.7.184.198:8150', 'quickbooks': 'http://28.7.184.198:8172', 'gmail': 'http://28.7.184.198:8138'}
_GO_CACHE = {}


def clamp01(x):
    return max(0.0, min(1.0, float(x)))


def frac(num, den):
    return 0.0 if den == 0 else num / den


def f1(true_set, pred_set):
    if not true_set and not pred_set:
        return 1.0
    tp = len(true_set & pred_set)
    if tp == 0:
        return 0.0
    prec = tp / len(pred_set)
    rec = tp / len(true_set)
    return 2 * prec * rec / (prec + rec)


def by_id(items, key='id'):
    return {it.get(key): it for it in (items or []) if isinstance(it, dict)}


def has_text(haystack, *needles):
    s = (haystack or '').lower()
    return any(n.lower() in s for n in needles)


def norm(s):
    return (str(s) if s is not None else '').strip().lower()


def _deal_amount(deal):
    if not isinstance(deal, dict):
        return 0.0
    line_items = deal.get('lineItems') or []
    if isinstance(line_items, list) and line_items:
        total = 0.0
        for item in line_items:
            if isinstance(item, dict):
                try:
                    total += float(item.get('amount', 0) or 0)
                except (TypeError, ValueError):
                    continue
        return total
    try:
        return float(deal.get('amount', 0) or 0)
    except (TypeError, ValueError):
        return 0.0

def _invoice_customer_name(iv):
    if not isinstance(iv, dict):
        return ''

    customer = iv.get('customer')
    if isinstance(customer, dict):
        return customer.get('name') or customer.get('displayName') or customer.get('customerName') or customer.get('fullName') or ''

    if isinstance(customer, list):
        for c in customer:
            if isinstance(c, dict):
                name = c.get('name') or c.get('displayName') or c.get('customerName') or c.get('fullName')
                if name:
                    return name
            elif c:
                return str(c)

    return customer or iv.get('customerName') or iv.get('name') or iv.get('displayName') or iv.get('customerDisplayName') or ''


def _invoice_total(iv):
    if not isinstance(iv, dict):
        return 0.0

    for key in ('total', 'amount', 'invoiceTotal', 'balance', 'totalAmount', 'amountDue', 'amount_total'):
        value = iv.get(key)
        if isinstance(value, dict):
            value = value.get('amount') or value.get('value')
        try:
            return float(value or 0)
        except (TypeError, ValueError):
            continue

    line_items = iv.get('lineItems') or iv.get('items') or iv.get('lines')
    if isinstance(line_items, list) and line_items:
        total = 0.0
        for item in line_items:
            if not isinstance(item, dict):
                continue
            raw = item.get('amount')
            if raw is None:
                qty = item.get('quantity', 1)
                unit = item.get('unitPrice') or item.get('rate') or item.get('price')
                try:
                    raw = float(qty or 0) * float(unit or 0)
                except (TypeError, ValueError):
                    raw = 0
            try:
                total += float(raw or 0)
            except (TypeError, ValueError):
                continue
        return total

    return 0.0


def _notes_text(deal):
    if not isinstance(deal, dict):
        return ''

    chunks = []
    notes = deal.get('notes', [])
    if isinstance(notes, list):
        for x in notes:
            if isinstance(x, dict):
                chunks.append(str(x.get('body') or x.get('content') or x.get('text') or x.get('note') or x))
            else:
                chunks.append(str(x))
    elif notes:
        chunks.append(str(notes))

    for key in ('activity', 'activities', 'timeline', 'comments'):
        value = deal.get(key)
        if isinstance(value, list):
            for v in value:
                if isinstance(v, dict):
                    chunks.append(str(v.get('body') or v.get('content') or v.get('text') or v.get('note') or v))
                else:
                    chunks.append(str(v))
        elif value:
            chunks.append(str(value))

    return ' '.join(chunks)


def _email_text(email):
    if not isinstance(email, dict):
        return str(email)

    to = email.get('to', '')
    if isinstance(to, list):
        to = ' '.join(
            (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
            for x in to
        )
    elif isinstance(to, dict):
        to = to.get('name') or to.get('email') or str(to)

    to_recips = email.get('toRecipients', [])
    if isinstance(to_recips, list):
        to_recips = ' '.join(
            (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
            for x in to_recips
        )
    else:
        to_recips = ''

    return f"{to} {to_recips} {email.get('subject', '')} {email.get('body', '')}"


def _gmail_sent_emails(gmail_state):
    out = []
    if not isinstance(gmail_state, dict):
        return out

    for e in gmail_state.get('emails', []):
        if not isinstance(e, dict):
            continue
        folder = norm(e.get('folder'))
        if folder in ('sent', 'sentitems', 'sent items'):
            out.append(e)
            continue
        if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
            out.append(e)

    if out:
        return out

    for key in ('sent', 'sentEmails', 'outbox'):
        items = gmail_state.get(key, [])
        if isinstance(items, list):
            out.extend(x for x in items if isinstance(x, dict))
    return out


def _normalize_app_name(app):
    app = (app or '').strip().lower()
    return app[:-5] if app.endswith('_mock') else app


def _parse_cell_id(cell_id):
    if not isinstance(cell_id, str) or not cell_id:
        return None
    idx = 0
    while idx < len(cell_id) and cell_id[idx].isalpha():
        idx += 1
    if idx == 0 or idx >= len(cell_id):
        return None
    col = 0
    for ch in cell_id[:idx].upper():
        col = col * 26 + (ord(ch) - ord('A') + 1)
    try:
        row = int(cell_id[idx:])
    except ValueError:
        return None
    return row, col - 1


def _extract_rows_from_workbook(state):
    if not isinstance(state, dict):
        return None
    sheets = state.get('sheets')
    if not isinstance(sheets, list):
        return None

    adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
    headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}

    out = {}
    for sh in sheets:
        if not isinstance(sh, dict):
            continue
        name = sh.get('name') or sh.get('id') or 'Sheet1'
        data = sh.get('data') if isinstance(sh.get('data'), dict) else {}

        headers = headers_by_sheet.get(name)
        if not headers:
            cols = []
            for cid, cell in data.items():
                rc = _parse_cell_id(cid)
                if not rc:
                    continue
                row_idx, col_idx = rc
                if row_idx != 1:
                    continue
                value = ''
                if isinstance(cell, dict):
                    value = cell.get('value', '')
                elif cell is not None:
                    value = str(cell)
                if value is not None and str(value) != '':
                    cols.append((col_idx, str(value)))
            headers = [v for _, v in sorted(cols)]

        if not headers:
            continue

        by_row = {}
        for cid, cell in data.items():
            rc = _parse_cell_id(cid)
            if not rc:
                continue
            row_idx, col_idx = rc
            if row_idx <= 1 or col_idx >= len(headers):
                continue
            if isinstance(cell, dict):
                value = cell.get('value', '')
            else:
                value = cell
            by_row.setdefault(row_idx, {})[headers[col_idx]] = value

        rows = []
        for row_idx in sorted(by_row.keys()):
            row = by_row[row_idx]
            if not any(str(row.get(h, '')).strip() for h in headers):
                continue
            rows.append({h: row.get(h, '') for h in headers})

        out[name] = {'headers': headers, 'rows': rows}

    if not out:
        return None
    return {'sheets': out}


def _materialize_google_sheets(payload):
    for key in ('initial_state', 'current_state'):
        state = payload.get(key)
        if not isinstance(state, dict):
            continue
        maybe_rows = _extract_rows_from_workbook(state)
        if maybe_rows is not None:
            state['_ui_workbook'] = {
                'sheets': copy.deepcopy(state.get('sheets', [])),
                'title': state.get('title'),
            }
            state['sheets'] = maybe_rows['sheets']


def _materialize_slack(payload):
    for key in ('initial_state', 'current_state'):
        state = payload.get(key)
        if not isinstance(state, dict):
            continue
        channels = state.get('channels') if isinstance(state.get('channels'), list) else []
        messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
        for ch in channels:
            if not isinstance(ch, dict):
                continue
            cid = ch.get('channelId') or ch.get('id')
            if not cid:
                continue
            msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
            channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
            merged = {
                (m.get('messageId') or m.get('id')): dict(m)
                for m in channel_msgs
                if isinstance(m, dict)
            }
            for m in msg_list:
                if not isinstance(m, dict):
                    continue
                mid = m.get('messageId') or m.get('id')
                text = m.get('text') if m.get('text') is not None else m.get('content', '')
                merged[mid] = {
                    'id': mid,
                    'messageId': mid,
                    'text': text,
                    'content': m.get('content', text),
                    'senderId': m.get('senderId'),
                    'timestamp': m.get('timestamp'),
                    'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
                }
            ch['messages'] = list(merged.values())


def _owner_name_map(state):
    out = {}
    users = state.get('users') if isinstance(state.get('users'), list) else []
    for u in users:
        if not isinstance(u, dict):
            continue
        uid = u.get('userId')
        if not uid:
            continue
        name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
        out[uid] = name
    return out


def _materialize_salesforce(payload):
    for key in ('initial_state', 'current_state'):
        state = payload.get(key)
        if not isinstance(state, dict):
            continue

        adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
        owner_names = _owner_name_map(state)

        task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
        if task_leads and isinstance(state.get('leads'), list):
            restored = []
            for lead in state['leads']:
                if not isinstance(lead, dict):
                    continue
                lid = str(lead.get('leadId') or lead.get('id') or '')
                meta = task_leads.get(lid, {})
                restored.append({
                    'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
                    'company': lead.get('company', meta.get('company', '')),
                    'status': lead.get('status', 'New'),
                    'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
                    'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
                })
            state['leads'] = restored

        task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
        if task_accounts and isinstance(state.get('accounts'), list):
            current_by_id = {}
            for acc in state['accounts']:
                if isinstance(acc, dict):
                    current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc

            restored_accounts = []
            for aid, meta in task_accounts.items():
                cur = current_by_id.get(str(aid), {})
                restored_accounts.append({
                    'id': meta.get('id') or aid,
                    'name': meta.get('name') or cur.get('name', ''),
                    'contact': meta.get('contact'),
                    'wonWithin7d': bool(meta.get('wonWithin7d', False)),
                    'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
                })
            state['accounts'] = restored_accounts


def _materialize_google_docs(payload):
    for key in ('initial_state', 'current_state'):
        state = payload.get(key)
        if not isinstance(state, dict):
            continue
        adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
        task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
        if not task_docs:
            continue
        docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
        restored = []
        for did, meta in task_docs.items():
            cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
            restored.append({
                'id': meta.get('id') or did,
                'title': cur.get('title', meta.get('title')),
                'vendor': meta.get('vendor'),
                'folder': meta.get('folder'),
                'content': cur.get('content', meta.get('content', '')),
            })
        state['documents'] = restored


def _adapt_payload_for_reward(app, payload):
    app_name = _normalize_app_name(app)
    if app_name == 'google_sheets':
        _materialize_google_sheets(payload)
    elif app_name == 'slack':
        _materialize_slack(payload)
    elif app_name == 'salesforce':
        _materialize_salesforce(payload)
    elif app_name == 'google_docs':
        _materialize_google_docs(payload)
    return payload


def go(app_name):
    if app_name in _GO_CACHE:
        return _GO_CACHE[app_name]

    base = APP_URLS.get(app_name)
    if not base:
        print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
        print('REWARD: 0.0')
        sys.exit(0)

    try:
        resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
        resp.raise_for_status()
        payload = resp.json()
    except Exception as e:
        print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
        print('REWARD: 0.0')
        sys.exit(0)

    payload = _adapt_payload_for_reward(app_name, payload)
    _GO_CACHE[app_name] = payload
    return payload


# === Task-specific reward (rewritten for new schema, per-deal weighted) ===
#
# Scoring model (B-mixed, decided 2026-06-15):
#   - Each April-Closed-Won deal contributes up to 1.0 to its own score.
#   - 6 sub-checks per deal, weights sum to 1.0:
#       A1 customer        0.15  invoice exists for this deal's company
#       A2 line item       0.20  exactly 1 item with the right product/qty/rate/amount
#                                (must also match customer name; A2 is self-contained
#                                and re-checks customer to prevent cross-deal mix-up)
#       A3 header          0.15  same invoice has terms/date/dueDate/tax/status correct
#                                (must also match customer name; self-contained)
#       B1 recipient       0.10  a sent gmail email addressed to the right contact
#       B2 email body      0.15  email's subject + body match the template anchors,
#                                with subject/body invoice number self-consistent.
#                                Independent of A* (does NOT require a real invoice).
#       C  description     0.25  deal.description contains "Invoiced INV-<digits>.".
#                                Independent of A* (does NOT require a real invoice).
#   - total_score = sum(deal_score(d) for d in won) / n
#   - n is the count of April-Closed-Won deals in the initial state.
#
# Dependency chain (B-mixed):
#   A1 -> A2 (re-checks customer) and A3 (re-checks customer): A group is integrated.
#   B1 -> B2 (re-checks recipient): B group is internally chained.
#   C is fully standalone (matches the literal pattern in description).
#   A and B and C are independent of each other.

import datetime as _dt
import re as _re

_INV_NUMBER_RE = _re.compile(r'Invoiced\s+INV-(\d+)\.', _re.IGNORECASE)


def _april_won_deals(deals_initial):
    out = []
    for d in deals_initial or []:
        if not isinstance(d, dict):
            continue
        if norm(d.get('stage')) != 'closedwon':
            continue
        close_date = (d.get('closeDate') or '').strip()
        if close_date.startswith('2026-04-'):
            out.append(d)
    return out


def _company_name_for_deal(deal, hubspot_initial):
    company_id = deal.get('companyId')
    for c in hubspot_initial.get('companies', []) or []:
        if isinstance(c, dict) and c.get('id') == company_id:
            return (c.get('name') or '').strip()
    return (deal.get('customer') or '').strip()


def _primary_contact_for_deal(deal, hubspot_initial):
    contact_ids = deal.get('contactIds') or []
    if not contact_ids:
        return None
    cid0 = contact_ids[0]
    for c in hubspot_initial.get('contacts', []) or []:
        if isinstance(c, dict) and c.get('id') == cid0:
            return c
    return None


def _qb_customer_name_by_id(qb_state):
    return {
        c.get('id'): (c.get('name') or '').strip()
        for c in (qb_state.get('customers') or [])
        if isinstance(c, dict) and c.get('id')
    }


def _qb_product_by_id(qb_state):
    return {
        p.get('id'): p
        for p in (qb_state.get('products') or [])
        if isinstance(p, dict) and p.get('id')
    }


def _add_days(date_str, days):
    try:
        d = _dt.datetime.strptime(date_str, '%Y-%m-%d').date()
    except (TypeError, ValueError):
        return ''
    return (d + _dt.timedelta(days=days)).isoformat()


def _invoice_items(iv):
    items = iv.get('items')
    if isinstance(items, list):
        return items
    items = iv.get('lineItems')
    if isinstance(items, list):
        return items
    return []


def _check_a1_customer(deal, hubspot_initial, invoices, qb_cust_by_id):
    target_name = norm(_company_name_for_deal(deal, hubspot_initial))
    if not target_name:
        return None
    for iv in invoices or []:
        if not isinstance(iv, dict):
            continue
        cust_name = norm(qb_cust_by_id.get(iv.get('customerId'), ''))
        if not cust_name:
            cust_name = norm(_invoice_customer_name(iv))
        if cust_name and cust_name == target_name:
            return iv
    return None


def _check_a2_line_item(deal, hubspot_initial, invoices, qb_cust_by_id, qb_prod_by_id):
    """Self-contained: find ANY invoice for the deal's company that has the right
    single line item. Independent of A1's pick (but typically returns same one)."""
    target_name = norm(_company_name_for_deal(deal, hubspot_initial))
    if not target_name:
        return False
    deal_name = deal.get('name') or ''
    if ' - ' not in deal_name:
        return False
    expected_product = deal_name.split(' - ', 1)[1].strip()
    deal_amt = _deal_amount(deal)

    for invoice in invoices or []:
        if not isinstance(invoice, dict):
            continue
        cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
        if not cust_name:
            cust_name = norm(_invoice_customer_name(invoice))
        if cust_name != target_name:
            continue
        items = _invoice_items(invoice)
        if len(items) != 1:
            continue
        item = items[0]
        if not isinstance(item, dict):
            continue
        product = qb_prod_by_id.get(item.get('productId')) or {}
        if norm(product.get('name', '')) != norm(expected_product):
            continue
        try:
            qty = float(item.get('qty', 0) or 0)
        except (TypeError, ValueError):
            qty = 0
        if abs(qty - 1.0) > 1e-6:
            continue
        try:
            rate = float(item.get('rate', 0) or 0)
            amt = float(item.get('amount', 0) or 0)
        except (TypeError, ValueError):
            continue
        if abs(rate - deal_amt) > 0.5 or abs(amt - deal_amt) > 0.5:
            continue
        return True
    return False


def _check_a3_header(deal, hubspot_initial, invoices, qb_cust_by_id):
    """Self-contained: find ANY invoice for the deal's company with correct header."""
    target_name = norm(_company_name_for_deal(deal, hubspot_initial))
    if not target_name:
        return False
    close_date = (deal.get('closeDate') or '').strip()
    expected_due = _add_days(close_date, 30)

    for invoice in invoices or []:
        if not isinstance(invoice, dict):
            continue
        cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
        if not cust_name:
            cust_name = norm(_invoice_customer_name(invoice))
        if cust_name != target_name:
            continue
        if norm(invoice.get('terms')) != 'net 30':
            continue
        if (invoice.get('date') or '').strip() != close_date:
            continue
        if (invoice.get('dueDate') or '').strip() != expected_due:
            continue
        try:
            tax = float(invoice.get('tax', 0) or 0)
        except (TypeError, ValueError):
            tax = 0
        if abs(tax) > 0.01:
            continue
        if norm(invoice.get('status')) != 'sent':
            continue
        return True
    return False


def _check_b1_recipient(deal, hubspot_initial, sent_emails):
    contact = _primary_contact_for_deal(deal, hubspot_initial)
    if not contact:
        return None
    target_email = norm(contact.get('email'))
    if not target_email:
        return None
    for e in sent_emails or []:
        if not isinstance(e, dict):
            continue
        if target_email in norm(_email_text(e)):
            return e
    return None


def _check_b2_email_body(deal, hubspot_initial, sent_emails):
    """Self-contained: find ANY sent email to the deal's primary contact whose
    subject contains 'Invoice #<n>', body contains 'INVOICE #<n>' (same <n>),
    'Total: $<deal.amount>', and 'Status: Sent'. Independent of any QB invoice."""
    contact = _primary_contact_for_deal(deal, hubspot_initial)
    if not contact:
        return False
    target_email = norm(contact.get('email'))
    if not target_email:
        return False
    deal_amt = _deal_amount(deal)
    amt_int = 'total: ${}'.format(int(round(deal_amt)))
    amt_dec = 'total: ${:.2f}'.format(deal_amt)
    subject_re = _re.compile(r'invoice\s*#\s*(\d+)')

    for e in sent_emails or []:
        if not isinstance(e, dict):
            continue
        if target_email not in norm(_email_text(e)):
            continue
        subject = norm(e.get('subject') or '')
        body = e.get('body') or ''
        body_text = _re.sub(r'<[^>]+>', ' ', body)
        nb = norm(body_text)

        m_sub = subject_re.search(subject)
        if not m_sub:
            continue
        n = m_sub.group(1)
        # Body must reference the SAME number (self-consistent).
        if 'invoice #{}'.format(n) not in nb:
            continue
        if amt_int not in nb and amt_dec not in nb:
            continue
        if 'status: sent' not in nb:
            continue
        return True
    return False


def _check_c_description(deal_current):
    """Self-contained: deal.description contains 'Invoiced INV-<digits>.'.
    Independent of any QB invoice. (Falls back to deal.notes for legacy agents.)"""
    if not deal_current:
        return False
    desc = deal_current.get('description') or ''
    if _INV_NUMBER_RE.search(desc):
        return True
    notes_text = _notes_text(deal_current)
    if _INV_NUMBER_RE.search(notes_text):
        return True
    return False


WEIGHTS = {
    'A1_customer':   0.15,
    'A2_line_item':  0.20,
    'A3_header':     0.15,
    'B1_recipient':  0.10,
    'B2_email':      0.15,
    'C_description': 0.25,
}


def reward(go):
    hubspot_i = go('hubspot').get('initial_state', {}) or {}
    hubspot_c = go('hubspot').get('current_state', {}) or {}
    qb_c = go('quickbooks').get('current_state', {}) or {}
    gmail_c = go('gmail').get('current_state', {}) or {}

    deals_i = hubspot_i.get('deals', []) or []
    deals_c_by_id = {
        d.get('id'): d
        for d in (hubspot_c.get('deals', []) or [])
        if isinstance(d, dict)
    }
    invoices = qb_c.get('invoices', []) or []
    qb_cust_by_id = _qb_customer_name_by_id(qb_c)
    qb_prod_by_id = _qb_product_by_id(qb_c)
    sent_emails = _gmail_sent_emails(gmail_c)

    won = _april_won_deals(deals_i)
    n = len(won)
    if n == 0:
        print('DEBUG_054e615f n=0 -> vacuous REWARD=1.0')
        return 1.0

    per_deal_lines = []
    pass_counts = {k: 0 for k in WEIGHTS}
    total = 0.0

    for d in won:
        deal_id = d.get('id')
        deal_current = deals_c_by_id.get(deal_id, {})

        # A1 picks an invoice for debug logging; A2/A3 are self-contained
        # but conceptually still belong to the same A group.
        invoice = _check_a1_customer(d, hubspot_i, invoices, qb_cust_by_id)

        checks = {
            'A1_customer':   invoice is not None,
            'A2_line_item':  _check_a2_line_item(d, hubspot_i, invoices, qb_cust_by_id, qb_prod_by_id),
            'A3_header':     _check_a3_header(d, hubspot_i, invoices, qb_cust_by_id),
            'B1_recipient':  _check_b1_recipient(d, hubspot_i, sent_emails) is not None,
            'B2_email':      _check_b2_email_body(d, hubspot_i, sent_emails),
            'C_description': _check_c_description(deal_current),
        }

        deal_score = 0.0
        for k, ok in checks.items():
            if ok:
                deal_score += WEIGHTS[k]
                pass_counts[k] += 1
        total += deal_score

        flags = ' '.join(
            '{}={}'.format(k.split('_', 1)[0], 'Y' if v else 'N')
            for k, v in checks.items()
        )
        company = _company_name_for_deal(d, hubspot_i) or '?'
        per_deal_lines.append(
            '  {} {:<12s}: score={:.3f}  {}'.format(deal_id, company, deal_score, flags)
        )

    score = total / n

    print('DEBUG_054e615f n={}'.format(n))
    for line in per_deal_lines:
        print(line)
    rates = '  '.join('{}={}/{}'.format(k.split('_', 1)[0], pass_counts[k], n) for k in WEIGHTS)
    print('sub-check pass rates: {}'.format(rates))
    print('total = sum / n = {:.4f} / {} = {:.4f}'.format(total, n, score))

    return clamp01(score)


try:
    score = float(reward(go))
except Exception as exc:
    print(f'ERROR: reward() raised {exc!r}')
    score = 0.0

score = clamp01(score)
print(f'\nREWARD: {round(score, 4)}')