"""blender --background --python import-site-context.py -- context.json output.blend
Builds a separate OSM context scene. Does not load or alter an existing house model.
Dataset: © OpenStreetMap contributors, ODbL 1.0. Preserve dataset and attribution.
"""
import bpy,json,sys,os
args=sys.argv[sys.argv.index('--')+1:]
if len(args)!=2:raise ValueError('Expected context.json output.blend')
d=json.load(open(args[0]))
if d.get('status')=='unavailable':raise ValueError('Context collection unavailable; do not create an empty model')
if d.get('schemaVersion')!=1 or 'openstreetmap' not in d.get('attribution','').lower():raise ValueError('Expected Rory OSM context export')
if os.path.exists(args[1]):raise ValueError('Choose a new output file; existing files are not overwritten')
bpy.ops.wm.read_factory_settings(use_empty=True)
col=bpy.data.collections.new('OSM context — not survey');bpy.context.scene.collection.children.link(col)
for b in d['buildings']:
 pts=b['points'];pts=pts[:-1] if pts[0]==pts[-1] else pts;n=len(pts)
 verts=[(p[0],p[1],z) for z in (0,b['height']) for p in pts]
 faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]+[(i,(i+1)%n,(i+1)%n+n,i+n) for i in range(n)]
 mesh=bpy.data.meshes.new('OSM footprint');mesh.from_pydata(verts,[],faces);mesh.update();obj=bpy.data.objects.new('OSM building '+str(b['id']),mesh);col.objects.link(obj);obj['source']=b['source'];obj['height_basis']=b['heightBasis']
for r in d['roads']:
 curve=bpy.data.curves.new('OSM road','CURVE');curve.dimensions='3D';curve.bevel_depth=.2;s=curve.splines.new('POLY');s.points.add(len(r['points'])-1)
 for p,xy in zip(s.points,r['points']):p.co=(xy[0],xy[1],.05,1)
 obj=bpy.data.objects.new('OSM road '+str(r['id']),curve);col.objects.link(obj)
scene=bpy.context.scene;scene.unit_settings.system='METRIC';scene['attribution']=d['attribution'];scene['license']=d['license'];scene['dataset_file']=os.path.abspath(args[0]);scene['origin']=json.dumps(d['origin']);scene['fetched_at']=d['fetchedAt'];scene['coordinates']='X east, Y north, Z up; metres'
text=bpy.data.texts.new('SOURCE AND LICENSE');text.write('© OpenStreetMap contributors. Data licensed under ODbL 1.0: '+d['license']+'\nKeep the source context JSON with shared outputs. Heights may be estimates; no municipal boundaries or Google-derived data.\n'+json.dumps(d,indent=2))
bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(args[1]))
print('Created separate OSM context scene:',args[1])
