"""List NONE-round LINK verdicts whose catalogue project already carries another realtycheck scheme.

Two schemes on one project is allowed (JPPH splits one complex into condo + serviced-apartment
schemes, or one estate by road range) — but it is also what a wrong link looks like, so every such
pair is printed for a human read: both schemes' names, sizes seen in their sales, and medians.
Usage: python3 none_link_collisions.py [case ...]   (default: every accepted LINK verdict)
"""
import glob, json, sys, collections

D = '/var/www/html/peta/storage/app/propertylab-catalogue-match'; R = f'{D}/review'
cat = json.load(open(f'{D}/catalogue_my_projects.json'))
rc = {r['scheme_id']: r for r in json.load(open(f'{D}/realtycheck_schemes.json'))}
links = json.load(open(f'{D}/final_links.json'))
adj = json.load(open(f'{R}/_none_adjudication.json'))
only = set(sys.argv[1:])

by_uuid = collections.defaultdict(list)
for o in links:
    if o['link'] == 'LINK' and o['cat_i'] is not None and 'NONE re-check' not in o['path']:
        by_uuid[cat[o['cat_i']]['uuid']].append(('first round', o['scheme_id'], o['confidence']))
verdicts = {}
for fn in sorted(glob.glob(f'{R}/n_*_out.jsonl')):
    for line in open(fn):
        if line.strip():
            v = json.loads(line); verdicts[v['case']] = v
packets = {}
for fn in sorted(glob.glob(f'{R}/n_*_in.jsonl')):
    for line in open(fn):
        if line.strip():
            p = json.loads(line); packets[p['case']] = p
for case, v in verdicts.items():
    if case in adj and v['decision'] == 'LINK' and int(v.get('confidence_pct') or 0) >= 90:
        by_uuid[v['uuid']].append((case, packets[case]['scheme_id'], v['confidence_pct']))

name = {c['uuid']: c['project_name'] for c in cat}
shown = 0
for u, members in by_uuid.items():
    if len(members) < 2 or not any(m[0] != 'first round' for m in members):
        continue
    if only and not any(m[0] in only for m in members):
        continue
    shown += 1
    print(f'\n{u[:8]} {name.get(u)}')
    for who, sid, conf in members:
        r = rc[sid]
        print(f'   {who:12s} {conf}% {r["display_name"]} [{r["category"]}] n={r["source_n"]} med RM{r["median_rm"]} psf {r["reported_psf"]} | {r["state"]} / {r["district"]} / {r["mukim"]}')
print(f'\n{shown} catalogue projects now carry 2+ schemes through a NONE-round link')
