"""Reproduce public local georeference and join the official SGIS boundaries. Requires openpyxl and shapely. No incident source is read."""
import json,pathlib,hashlib,collections
import openpyxl
from shapely.geometry import shape,Point
ROOT=pathlib.Path(__file__).resolve().parents[1]
# ROOT is geo/. Original archive reads are BUILDING-only inputs.

SRC=pathlib.Path("/home/leeai/data/kict-archive/원본/------------논문프로젝트들/화재'")
xs_path=SRC/'건축물데이터(도형+대장)_2025-07-25.xlsx';gj_path=SRC/'건축물데이터(도형+대장)_2025-07-25.geojson'
wb=openpyxl.load_workbook(xs_path,read_only=True);ws=wb.worksheets[0];ws.reset_dimensions();rows=ws.iter_rows(values_only=True);head=list(next(rows));I={}
for i,c in enumerate(head):I.setdefault(c,i)
reg={r[I['건물관리번호']] for r in rows if r[I['산업단지분류']]=='명지녹산'}
gj=json.loads(gj_path.read_text());feats=[f for f in gj['features'] if f['properties']['건물관리번호'] in reg]
def rings(g):return [g['coordinates'][0]] if g['type']=='Polygon' else [p[0] for p in g['coordinates']]
def first_x(f):return rings(f['geometry'])[0][0][0]
xs=sorted(first_x(f) for f in feats);gap=max(range(1,len(xs)),key=lambda i:xs[i]-xs[i-1]);cut=(xs[gap]+xs[gap-1])/2;feats=[f for f in feats if first_x(f)<cut]
xy=[p for f in feats for r in rings(f['geometry']) for p in r];cx=(min(x for x,y in xy)+max(x for x,y in xy))/2;cy=(min(y for x,y in xy)+max(y for x,y in xy))/2
local=json.loads((ROOT/'spatial-statistics/data/noksan.json').read_text())['buildings'];diff=[];offsets=[]
assert len(feats)==len(local)==2233
for i,(f,b) in enumerate(zip(feats,local)):
 r=rings(f['geometry']);pred=[[[round((x-cx)*2)/2,round((y-cy)*2)/2] for x,y in ring] for ring in r]
 if pred!=b['p']:diff.append(i)
 if i<3:offsets.append([r[0][0][0]-b['p'][0][0][0],r[0][0][1]-b['p'][0][0][1]])
boundary_path=ROOT/'evidence/sources/g4/sgis-gangseo-2025.geojson'
bound=json.loads(boundary_path.read_text());assert bound.get('errCd')==0 and len(bound['features'])==9
assert 'img_opencode1_m.jpg' in (ROOT/'evidence/sources/g4/sgis-api-license-original.html.txt').read_text()
polys=[(f['properties']['adm_cd'],f['properties']['adm_nm'],shape(f['geometry'])) for f in bound['features']]
counts=collections.Counter();mismatch=0;near=[];assignments=[];distances=[]
for i,b in enumerate(local):
 c=Point(b['center'][0]+cx,b['center'][1]+cy);hit=[(cd,nm) for cd,nm,p in polys if p.covers(c)];counts.update(cd for cd,nm in hit)
 if len(hit)!=1:mismatch+=1
 assignments.append(hit[0][0] if len(hit)==1 else None)
 d=min(p.boundary.distance(c) for cd,nm,p in polys)
 distances.append(d)
 if d<1:near.append([i,d])
out={'method':'Reproduce works/scripts/build_noksan.py selection and half-metre rounding; compare every output ring with permitted local public JSON. Original xlsx read only building metadata; original GeoJSON only building polygons. No fire/casualty dataset read.','sourceHashes':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [xs_path,gj_path]},'count':len(local),'originEPSG5179':[cx,cy],'localRoundM':0.5,'maxVertexRoundErrorM':0.25,'geometryDifferenceCount':len(diff),'geometryDifferences':diff,'boundaryYear':2025,'boundaryFeatures':len(polys),'dongCounts':dict(counts),'unmatchedOrMultiple':mismatch,'within1mOfBoundary':near,'boundarySource':'https://sgis.mods.go.kr/ServiceAPI/OpenAPI3/boundary/hadmarea.geojson?year=2025&adm_cd=21120&low_search=1'}

assert not diff and not mismatch, "Stop: geometry reproduction or boundary assignment failed"
out.pop('maxVertexRoundErrorM',None)
out.update(maxVertexRoundErrorPerAxisM=.25,maximumVertexRoundEuclideanM=2**.5*.25,nearestCentroidToBoundaryM=min(distances),boundarySha256=hashlib.sha256(boundary_path.read_bytes()).hexdigest(),licenseSource='https://www.data.go.kr/data/15021230/openapi.do',redistributionStatus='Official SGIS API catalog 15021230 original read: third-party attribution and KOGL Type 1. Preserve SGIS attribution.')
public_path=ROOT/'spatial-statistics/data/noksan.json';out['publicInputSha256']=hashlib.sha256(public_path.read_bytes()).hexdigest()
out['adminSummary']={'nonemptyUnits':len(counts),'count':len(local),'name':'녹산동','knownYears':sum(bool(b.get('y')) for b in local),'approvalYear2000OrEarlier':sum(bool(b.get('y')) and b['y']<=2000 for b in local),'meanHeight':sum(b['h'] for b in local)/len(local),'rHeight':None,'rAge':None,'rankRho':None,'undefinedReason':'One occupied administrative unit; attached rank variance is zero.'}
prepared={'source':out['boundarySource'],'licenseSource':out['licenseSource'],'license':'KOGL Type 1; attribution required. Official catalog 15021230 also marks third-party attribution.','attribution':'국가데이터처 SGIS 통계지리정보서비스 · 2025 센서스 행정구역경계 · 공공누리 제1유형','crs':'EPSG:5179','localOrigin':[cx,cy],'boundaryYear':2025,'inputBuildings':len(local),'names':{f['properties']['adm_cd']:f['properties']['adm_nm'] for f in bound['features']},'assignments':assignments,'features':bound['features']}
(ROOT/'spatial-statistics/data/administrative.json').write_text(json.dumps(prepared,ensure_ascii=False,separators=(',',':')))
(ROOT/'evidence/G4-administrative-validation.json').write_text(json.dumps(out,ensure_ascii=False,indent=2))
print(json.dumps({k:out[k] for k in ['count','geometryDifferenceCount','dongCounts','unmatchedOrMultiple','nearestCentroidToBoundaryM']},ensure_ascii=False,indent=2))
