"""Combine the earlier verdict with the blind second opinion; list what needs Claude's adjudication."""
import json, glob, collections, os, sys
D = '/var/www/html/peta/storage/app/propertylab-catalogue-match'; R = f'{D}/review'
rc = {r['scheme_id']: r for r in json.load(open(f'{D}/realtycheck_schemes.json'))}
cat = json.load(open(f'{D}/catalogue_my_projects.json'))
final = {f['scheme_id']: f for f in json.load(open(f'{D}/final.json'))}
key3 = json.load(open(f'{R}/_key3.json'))
adj = json.load(open(f'{R}/_adjudications.json')) if os.path.exists(f'{R}/_adjudications.json') else {}
v = {}
for fn in sorted(glob.glob(f'{R}/v_*_out.jsonl')):
    for line in open(fn):
        if line.strip():
            x = json.loads(line); v[x['case']] = x
twins = collections.defaultdict(set)
for f in final.values():
    if f['best_i'] is not None:
        for t in f['twins']: twins[f['best_i']].add(t); twins[t].add(f['best_i'])
def same_dev(a, b): return a == b or b in twins[a]
PRIOR = {'SAME - confident': 'SAME', 'SAME - probable': 'SAME', 'PART OF (phase / block / sub-estate)': 'PART_OF', 'NEEDS HUMAN CHECK': 'UNSURE'}
outcome, todo = {}, []
for cid, k in key3.items():
    f = final[k['scheme_id']]; x = v.get(cid)
    if not x: continue
    pv, pc = PRIOR[f['status']], f['cat_i']
    c = x.get('cand'); vc = k['cand_i'][c] if isinstance(c, int) and 0 <= c < len(k['cand_i']) else None
    conf = x.get('confidence_pct') or 0; vv = x['verdict']
    if cid in adj:
        outcome[cid] = ('adjudicated', adj[cid]); continue
    if pv == 'SAME' and vv == 'SAME' and vc is not None and same_dev(pc, vc):
        res = ('agree_same', vc if vc == pc else pc) if conf >= 80 else ('adjudicate', 'agree but low confidence')
    elif pv == 'PART_OF' and vv == 'PART_OF' and vc is not None and same_dev(pc, vc):
        res = ('agree_part', pc)
    elif pv == 'UNSURE' and vv in ('DIFFERENT', 'UNSURE'):
        res = ('no_link', None)
    elif pv in ('SAME', 'PART_OF') and vv == 'DIFFERENT' and conf >= 90 and f['status'] != 'SAME - confident':
        res = ('adjudicate', 'second opinion says different')
    else:
        res = ('adjudicate', f'{pv}->{vv}')
    outcome[cid] = res
    if res[0] == 'adjudicate': todo.append(cid)
seg = lambda c: 'high-rise' if rc[key3[c]['scheme_id']]['category'] in ('Condo/Apartment', 'Serviced Apartment', 'Flat') else 'landed' if rc[key3[c]['scheme_id']]['category'] == 'Landed' else 'commercial'
t = collections.Counter((seg(c), o[0]) for c, o in outcome.items())
for s in ('high-rise', 'landed', 'commercial'):
    print(s, {k2: t[(s, k2)] for k2 in ('agree_same', 'agree_part', 'no_link', 'adjudicate', 'adjudicated')})
print('second opinions in:', len(v), '/', len(key3), '| to adjudicate:', len(todo))
json.dump(outcome, open(f'{R}/_verify_outcome.json', 'w'))
json.dump(todo, open(f'{R}/_to_adjudicate.json', 'w'))
