# -*- coding: utf-8 -*-
# sales-reps.json を名店マスターの各storeの salesReps に反映。
import json, os
HERE = os.path.dirname(os.path.abspath(__file__))
SRC  = os.path.join(HERE, "meiten-master.json")
REP  = os.path.join(HERE, "sales-reps.json")

with open(SRC, encoding="utf-8") as f: j = json.load(f)
with open(REP, encoding="utf-8") as f: reps = json.load(f)

n=0; withrep=0
for s in j.get("stores", []):
    r = reps.get(s.get("storeId"))
    lst = []
    if isinstance(r, list): lst = r
    elif isinstance(r, dict): lst = r.get("salesReps", []) or []
    s["salesReps"] = lst
    if lst: withrep+=1
    n+=1

j["_meta"]["salesReps"] = "2026-06-06: 営業担当×担当号を付与（出典: 発注書06/配布08/CANDIDATES/ad-master。号不明は note明記）。"
with open(SRC,"w",encoding="utf-8") as f: json.dump(j,f,ensure_ascii=False,indent=2)
print("stores:",n,"with salesReps:",withrep)
# rep union
u={}
for s in j["stores"]:
    for r in s.get("salesReps",[]):
        if r.get("rep"): u[r["rep"]]=u.get(r["rep"],0)+1
print("reps:", ", ".join(f"{k}:{v}" for k,v in sorted(u.items(), key=lambda x:-x[1])))
