import json,collections,os
M=json.load(open(os.path.join(os.path.dirname(__file__),'..','measure_v3.json')))
L=[]
def P(*a):L.append(' '.join(str(x) for x in a))
bad=collections.defaultdict(list)
for k,cards in M.items():
  w=int(k.split('|')[0])
  for o in cards:
    if o['clip']:bad['clip'].append((k,o['sc'],o['clip']))
    for p in o['pills']:
      if p['overflow']:bad['pill-overflow'].append((k,o['sc'],p['text']))
      if 'mk-red' in p['cls']:
        if abs(p['icon_cy']-15)>.05 or abs(p['cd_cy']-15)>.06 or abs(p['left_gap']-p['right_gap'])>1:bad['red'].append((k,o['sc'],p))
      elif 'icon_cy' in p and (abs(p['icon_cy']-15)>.05 or abs(p['cd_cy']-15)>.06):bad['pill-mid'].append((k,o['sc'],p['cls'],p['icon_cy'],p['cd_cy']))
    # arrows: identical size/stroke/path; cy equal; trend arrows share right edge
    ars=[a for p in o['pills'] for a in p['arrows']]
    sig={(a['w'],a['h'],a['sw'],a['d'],a['stroke']) for a in ars}
    if len(sig)>1:bad['arrow-sig'].append((k,o['sc'],sig))
    cys={a['cy'] for a in ars}
    if cys and max(cys)-min(cys)>.05:bad['arrow-cy'].append((k,o['sc'],cys))
    tr=[a['right'] for p in o['pills'] if 'wfzl2' in p['cls'] and 'mk-min' not in p['cls'] for a in p['arrows']]
    if tr and max(tr)-min(tr)>.05:bad['trend-right'].append((k,o['sc'],tr))
    if o.get('fc'):
      if o['fc']['dot']:bad['dot'].append((k,o['sc']))
      for wd in o['fc']['words']:
        if wd.get('cr') is not None and wd['k']!='none' and wd['cr']<4.5:bad['fc-AA'].append((k,o['sc'],wd['k'],wd['cr'],wd['cs'],wd['bg']))
    b=o.get('badge')
    if b and b.get('cr') and b['text'] and o['sc']!='loading' and b['cr']<4.5 and o['badge']['text'] in('DEPART','LAND','CAUTION') and '|pearl|' in k or b and b.get('cr') and o['sc']!='loading' and b['cr']<4.5 and b['text'] in('DEPART','LAND','CAUTION') and '|champagne|' in k:bad['badge-AA-1C'].append((k,o['sc'],b['text'],b['cr']))
    if b and b.get('cr') and b['cr']<4.5 and b['text'] in ('NO DEPART','NO LAND'):bad['info-red-badge-below-AA'].append((k.split('|')[1],b['cr']))
    if b and (abs(b['top']-24)>.05 or abs(b['right']-20)>.05 or b['w']!=112 or b['h']!=28):bad['badge-pos'].append((k,o['sc'],b))
    if o.get('daWarn') and o['daWarn']['cr']<4.5:bad['daWarn-AA'].append((k,o['sc'],o['daWarn']['cr']))
    if o.get('mid') and max(o['mid'].values())-min(o['mid'].values())>.6:bad['wx-mid'].append((k,o['sc'],o['mid']))
    if 'viewInset' in o and abs(o['viewInset']-20)>.6:bad['view'].append((k,o['sc'],o['viewInset']))
  # equal heights per row
  rows=collections.defaultdict(list)
  for o in cards:rows[round(o['y'])].append(o['h'])
  for y,hs in rows.items():
    if max(hs)-min(hs)>.6:bad['row-height'].append((k,y,hs))
for kk in ['clip','pill-overflow','red','pill-mid','arrow-sig','arrow-cy','trend-right','dot','fc-AA','badge-AA-1C','info-red-badge-below-AA','badge-pos','daWarn-AA','wx-mid','view','row-height']:
  P(kk, 'PASS' if not bad[kk] else 'FAIL %d'%len(bad[kk]))
  for x in bad[kk][:6]:P('   ',x)
# detail tables
P('\nRED PILLS');
for k,cards in M.items():
  for o in cards:
    for p in o['pills']:
      if 'mk-red' in p['cls']:P(k,o['sc'],'icon_cy',p['icon_cy'],'cd_cy',p['cd_cy'],'glyph_cy',p['text_cy'],'L',p['left_gap'],'R',p['right_gap'],p['text'])
P('\nARROWS (390 midnight states)')
for o in M['390|midnight|states']:
  for p in o['pills']:
    for a in p['arrows']:P(o['sc'],p['text'][:3],a['slot'],a['dir'],a['w'],'x',a['h'],'sw',a['sw'],'cy',a['cy'],'x',a['x'],'right',a['right'],'pillR',p['pill_inner_right'])
P('\nFLIGHT WORDS (states, 4 themes, 390)')
for th in ('midnight','amethyst','pearl','champagne'):
  for o in M[f'390|{th}|states']:
    if o.get('fc'):P(th,o['sc'],' | '.join(f"{w['k']} {w['cs']} {w.get('cr')}:1" for w in o['fc']['words']))
P('\nBADGE AA (light themes)')
for th in ('pearl','champagne','midnight','amethyst'):
  for o in M[f'390|{th}|states']:
    b=o.get('badge')
    if b and b.get('cr'):P(th,o['sc'],b['text'],b['col'],b['bg'],b['cr'])
P('\nDA warn'); 
for k,cards in M.items():
  for o in cards:
    if o.get('daWarn') and k.startswith('390') :P(k,o['sc'],o['daWarn']['col'],o['daWarn']['cr'])
P('\nWX MIDLINE 390 midnight')
for o in M['390|midnight|states']:P(o['sc'],o.get('mid'))
P('\nROWS 1440 board');rows=collections.defaultdict(list)
for o in M['1440|midnight|board']:rows[round(o['y'])].append((o['sc'],o['h'],o.get('viewInset')))
for y,v in sorted(rows.items()):P(y,v)
open(os.path.join(os.path.dirname(__file__),'..','CHECKS.txt'),'w').write('\n'.join(L));print('\n'.join(L[:60]))
