import json,math,pathlib,argparse
parser=argparse.ArgumentParser()
parser.add_argument("dwg_json")
parser.add_argument("output_dir")
args=parser.parse_args()
D=json.load(open(args.dwg_json));B={b['name']:b for b in D['tables']['BLOCK_RECORD']['entries']};out={}
for lev in [2,3]:
 es=B[str(lev)]['entities'];ox=768808.48367232+(lev-2)*65000;oy=657172.066631896
 def pt(p):return [round((p['x']-ox)/1000,4),round((oy-p['y'])/1000,4)]
 f={'outline':[], 'walls':[], 'wallLines':[], 'windows':[], 'doors':[], 'tables':[], 'labels':[], 'stairs':[]}
 for e in es:
  typ=e['type'];layer=e['layer']
  if typ=='LWPOLYLINE' and layer=='A-AREA' and not f['outline']:f['outline']=[pt(p) for p in e['vertices']]
  if typ=='HATCH':
   for path in e['boundaryPaths']:
    if path.get('vertices'):f['walls'].append([pt(p) for p in path['vertices']])
  if typ=='LINE' and layer=='A-WALL':f['wallLines'].append([pt(e['startPoint']),pt(e['endPoint'])])
  if typ=='LINE' and layer=='A-STAIR':f['stairs'].append([pt(e['startPoint']),pt(e['endPoint'])])
  if typ in ['TEXT','MTEXT'] and layer=='A-PUB_TEXT':f['labels'].append({'text':e['text'],'p':pt(e.get('startPoint',e.get('insertionPoint')))})
  if typ=='INSERT':
   if e['name'] in ['zseEWEW','A$C3B814A28']:
    v=next(k['vertices'] for k in B[e['name']]['entities'] if k['type']=='LWPOLYLINE');xs=[p['x'] for p in v];ys=[p['y'] for p in v];cx=(min(xs)+max(xs))/2*e['xScale'];cy=(min(ys)+max(ys))/2*e['yScale'];r=e['rotation'];p=e['insertionPoint'];pos={'x':p['x']+cx*math.cos(r)-cy*math.sin(r),'y':p['y']+cx*math.sin(r)+cy*math.cos(r)}
    f['tables'].append({'p':pt(pos),'w':round((max(xs)-min(xs))*abs(e['xScale'])/1000,4),'d':round((max(ys)-min(ys))*abs(e['yScale'])/1000,4),'r':r,'handle':e['handle']})
   if layer=='A-WINDOW':
    rec={'p':pt(e['insertionPoint']),'w':round(abs(e['xScale'])/1000,4),'d':round(abs(e['yScale'])/1000,4),'r':e['rotation'],'sx':e['xScale']/1000,'sy':e['yScale']/1000}
    if 'WIN' in e['name']:f['windows'].append(rec)
    else:f['doors'].append(rec)
 out[str(lev)]=f
out['meta']={'bounds':[32.9,73.0],'unit':'m','dwgWarnings':68,'floorHeight':4.5,'heightStatus':'assumed','seatAnnotation':870,'tableBlocks':len(out['2']['tables'])}
p=pathlib.Path(args.output_dir);p.mkdir(exist_ok=True)
(p/'model.json').write_text(json.dumps(out,ensure_ascii=False,separators=(',',':')))
print({k:{a:len(v) for a,v in f.items() if isinstance(v,list)} for k,f in out.items()})
