# -*- coding: utf-8 -*-
# integration-patch.json をマスターへマージ：Vol.15紐づけ＋新規顧客追加＋ベスト100をL6潜在統合。
import json, os, re, urllib.parse
HERE=os.path.dirname(os.path.abspath(__file__))
SRC=os.path.join(HERE,"meiten-master.json")
PATCH=os.path.join(HERE,"..","mvp","source","integration-patch.json")
with open(SRC,encoding="utf-8") as f: j=json.load(f)
with open(PATCH,encoding="utf-8") as f: p=json.load(f)

LBLGROUP={"L1a":"継続広告主","L1b":"継続広告主","L1c":"継続広告主","L1d":"継続広告主","L2":"途絶★再コンタクト","L3":"埋蔵金(取材済未広告)","L4":"グループ内","L5":"域外/大手","L6":"未接触/新規開拓"}
def gmap(name,address):
    return "https://www.google.com/maps/search/?api=1&query="+urllib.parse.quote(((name or "")+" "+(address or "")).strip())
def derive_tags(s, extra=None):
    t=[];g=LBLGROUP.get(s.get("label"))
    if g:t.append(g)
    w=(s.get("area")or{}).get("ward"); t.append(w) if w else None
    tn=(s.get("area")or{}).get("town"); t.append(tn) if tn else None
    for piece in (s.get("category")or"").replace("／","・").split("・"):
        piece=piece.strip()
        if piece and piece not in t:t.append(piece)
    if 15 in (s.get("issuesPlaced")or[]):t.append("Vol.15出稿")
    v=s.get("vol15") or {}
    if v.get("status")=="受注":t.append("Vol.15受注")
    elif v.get("status")=="商談中":t.append("Vol.15商談中")
    elif v.get("status")=="未着手":t.append("Vol.15未着手")
    if s.get("lapsed"):t.append("途絶")
    if (s.get("tegataFit")or{}).get("level")=="高":t.append("手形適性高")
    if s.get("hotelEastFit")=="高":t.append("ホテル送客高")
    if s.get("potentialTier"):t.append("ポテンシャル"+s["potentialTier"])
    if s.get("rating") and s["rating"].get("score"):
        try:
            if float(str(s["rating"]["score"]).split()[0])>=3.5:t.append("高評価")
        except:pass
    for x in (extra or []): t.append(x)
    seen=set();out=[]
    for x in t:
        if x and x not in seen:seen.add(x);out.append(x)
    return out

by={s["storeId"]:s for s in j["stores"]}
nums=[int(re.sub(r"\D","",s["storeId"])) for s in j["stores"] if re.sub(r"\D","",s["storeId"])]
nextn=max(nums)+1
def newid():
    global nextn; sid=f"MTN-{nextn:03d}"; nextn+=1; return sid

stat={"vol15":0,"newcust":0,"b100_match":0,"b100_new":0}

# 1) Vol.15 紐づけ
for sid,u in (p.get("vol15Updates") or {}).items():
    s=by.get(sid)
    if not s: continue
    s["vol15"]={"status":u.get("vol15Status"),"slot":u.get("vol15Slot"),"amount":u.get("vol15Amount"),
                "rep":u.get("vol15Rep"),"mado":u.get("vol15Mado"),"invoiceStatus":u.get("invoiceStatus"),"invoiceKey":u.get("invoiceKey")}
    if u.get("vol15Status")=="受注":
        if 15 not in (s.get("issuesPlaced") or []): s.setdefault("issuesPlaced",[]).append(15)
        s["status"]="Vol.15受注"
        if u.get("vol15Amount"): s["lastSpend"]=u["vol15Amount"]
        rep=(u.get("vol15Rep") or "").strip()
        if rep:
            reps=s.setdefault("salesReps",[])
            if not any(r.get("rep")==rep and 15 in (r.get("issues") or []) for r in reps):
                reps.append({"rep":rep,"issues":[15],"note":"Vol.15(請求書管理)"})
    s["tags"]=derive_tags(s)
    stat["vol15"]+=1

# 2) 新規顧客
for nc in (p.get("newCustomers") or []):
    sid=newid()
    s={"storeId":sid,"name":nc.get("name"),"nameNormalized":nc.get("nameNormalized") or nc.get("name"),
       "category":nc.get("category") or "不明","area":nc.get("area") or {"ward":"台東区","town":""},
       "address":nc.get("address") or "台東区","lat":None,"lng":None,
       "label":nc.get("label") or "L1d","labelNote":"15号で新規受注（CEO営業シート由来）",
       "issuesPlaced":[15] if nc.get("vol15Status")=="受注" else [],
       "lastIssue":15 if nc.get("vol15Status")=="受注" else None,
       "status":"Vol.15"+(nc.get("vol15Status") or ""),"contractType":"単発",
       "spendKnownTotal":nc.get("vol15Amount"),"lastSpend":nc.get("vol15Amount"),"lapsed":False,
       "potentialTier":"B","tegataFit":{"level":"中","reason":"新規・要評価"},"hotelEastFit":"中","worldviewFit":"要評価",
       "vol15":{"status":nc.get("vol15Status"),"slot":nc.get("vol15Slot"),"amount":nc.get("vol15Amount"),
                "rep":nc.get("vol15Rep"),"mado":nc.get("vol15Mado"),"invoiceStatus":nc.get("invoiceStatus"),"invoiceKey":nc.get("invoiceKey")},
       "officialSite":nc.get("officialSite") or "不明","rating":None,
       "reviewComment":nc.get("source") or "15号で新規受注","researchConfidence":"新規(15号)",
       "salesReps":[{"rep":(nc.get("vol15Rep") or "").strip(),"issues":[15],"note":"Vol.15新規"}] if (nc.get("vol15Rep")) else []}
    s["googleMapsUrl"]=gmap(s["name"],s["address"]); s["tags"]=derive_tags(s,["新規顧客"])
    j["stores"].append(s); by[sid]=s; stat["newcust"]+=1

# 3) ベスト100
for b in (p.get("best100") or []):
    mid=b.get("matchedStoreId")
    if mid and mid in by:
        s=by[mid]
        s["bizDevNote"]=b.get("salesPoint") or s.get("bizDevNote")
        if b.get("deptContact"): s["deptContact"]=b["deptContact"]
        if b.get("phone") and not s.get("phone"): s["phone"]=b["phone"]
        if b.get("rank"): s["best100Rank"]=b["rank"]
        s["tags"]=derive_tags(s,["潜在営業","ベスト100"])
        stat["b100_match"]+=1
    else:
        sid=newid()
        s={"storeId":sid,"name":b.get("name"),"nameNormalized":b.get("nameNormalized") or b.get("name"),
           "category":b.get("category") or "不明","area":b.get("area") or {"ward":"台東区","town":""},
           "address":b.get("address") or "台東区","lat":None,"lng":None,
           "label":"L6","labelNote":"ベスト100 潜在営業ターゲット（未接触）",
           "issuesPlaced":[],"lastIssue":None,"status":"潜在","contractType":"未","spendKnownTotal":0,"lastSpend":None,"lapsed":False,
           "potentialTier":"B","tegataFit":{"level":"低","reason":"大手/BtoB中心・潜在"},"hotelEastFit":"低","worldviewFit":"要評価",
           "officialSite":b.get("officialSite") or "不明","rating":None,
           "reviewComment":b.get("note") or "","bizDevNote":b.get("salesPoint") or "",
           "deptContact":b.get("deptContact") or "","phone":b.get("phone") or "","best100Rank":b.get("rank"),
           "researchConfidence":"ベスト100(未接触)","salesReps":[]}
        s["googleMapsUrl"]=gmap(s["name"],s["address"]); s["tags"]=derive_tags(s,["潜在営業","ベスト100"])
        j["stores"].append(s); by[sid]=s; stat["b100_new"]+=1

j["_meta"]["integration"]="2026-06-06: CEO営業シート(13jmH)統合。Vol.15受注/請求紐づけ＋新規顧客＋ベスト100をL6潜在営業として統合。"
with open(SRC,"w",encoding="utf-8") as f: json.dump(j,f,ensure_ascii=False,indent=2)
print("stat:",stat,"total stores:",len(j["stores"]))
