# -*- coding: utf-8 -*-
# 担当を事前割当：claimedBy 未設定の店に、salesReps の主担当を自動セット（後から変更可）。
# 主担当＝Vol.15担当 > 最多関与 > 先頭。無ければ「担当未定」。
import json, os
SRC=os.path.join(os.path.dirname(os.path.abspath(__file__)),"meiten-master.json")
j=json.load(open(SRC,encoding="utf-8"))
def primary_rep(s):
    reps=s.get("salesReps") or []
    if not reps: return None
    # Vol.15(issues含15) を優先、次に issues数最多
    best=None; bestscore=-1
    for r in reps:
        if not r.get("rep"): continue
        iss=r.get("issues") or []
        score=(100 if 15 in iss else 0)+len(iss)
        if score>bestscore: bestscore=score; best=r["rep"]
    return best
auto=0; undef=0; kept=0
for s in j["stores"]:
    if s.get("claimedBy"):
        kept+=1; continue
    pr=primary_rep(s)
    # vol16/vol15 の rep も補完候補
    if not pr:
        for k in ("vol16","vol15"):
            v=s.get(k) or {}
            if v.get("rep") and v["rep"]!="未割当": pr=v["rep"]; break
    if pr:
        s["claimedBy"]=pr; s["claimedAuto"]=True; auto+=1
    else:
        s["claimedBy"]="担当未定"; s["claimedAuto"]=True; undef+=1
json.dump(j,open(SRC,"w",encoding="utf-8"),ensure_ascii=False,indent=2)
from collections import Counter
c=Counter(s.get("claimedBy") for s in j["stores"])
print(f"auto={auto} undef={undef} kept={kept}")
print("担当別店数:", dict(sorted(c.items(), key=lambda x:-x[1])))
