# -*- coding: utf-8 -*-
# geo-patch.json の座標をマスターへ反映（アトミック書込）。
import json, os, tempfile
B=os.path.dirname(os.path.abspath(__file__))
M=os.path.join(B,"meiten-master.json"); G=os.path.join(B,"geo-patch.json")
j=json.load(open(M,encoding="utf-8")); g=json.load(open(G,encoding="utf-8"))
patch=g.get("stores",g) if isinstance(g,dict) else {}
# geo-patch はフラット {MTN:{lat,lng,geocodeStatus}} 形式想定。_metaは除外。
n=0
by={s["storeId"]:s for s in j["stores"]}
for sid,v in patch.items():
    if not isinstance(v,dict) or "lat" not in v: continue
    s=by.get(sid)
    if not s: continue
    if s.get("lat") is None:
        s["lat"]=v["lat"]; s["lng"]=v["lng"]; s["geocodeStatus"]=v.get("geocodeStatus","confirmed"); n+=1
# アトミック書込
fd,tmp=tempfile.mkstemp(dir=B,suffix=".tmp"); os.close(fd)
json.dump(j,open(tmp,"w",encoding="utf-8"),ensure_ascii=False,indent=2)
os.replace(tmp,M)
withgeo=len([s for s in j["stores"] if s.get("lat") is not None])
print(f"merged coords:{n} / 座標あり店数:{withgeo}/{len(j['stores'])}")
