# -*- coding: utf-8 -*-
# research-resweep.json の確定分を名店マスターへ反映。確認済のみ住所/業種/名称/公式を更新。
# 要ヒアリングは reviewComment と researchConfidence のみ更新（住所は上書きしない）。
import json, os, urllib.parse
HERE=os.path.dirname(os.path.abspath(__file__))
SRC=os.path.join(HERE,"meiten-master.json")
RSW=os.path.join(HERE,"research-resweep.json")
with open(SRC,encoding="utf-8") as f: j=json.load(f)
with open(RSW,encoding="utf-8") as f: rsw=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):
    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 p in (s.get("category")or"").replace("／","・").split("・"):
        p=p.strip()
        if p and p not in t:t.append(p)
    if 15 in (s.get("issuesPlaced")or[]):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
    seen=set();out=[]
    for x in t:
        if x not in seen:seen.add(x);out.append(x)
    return out

stat={"confirmed":0,"hearing":0,"addr":0,"site":0,"cat":0}
by={s.get("storeId"):s for s in j["stores"]}
rsw_stores = rsw.get("stores", rsw) if isinstance(rsw, dict) else {}
for sid,r in rsw_stores.items():
    if not isinstance(r, dict): continue
    if sid not in by: continue
    s=by[sid]; conf=(r.get("confidence") or "")
    changed=False
    if "確認済" in conf:
        stat["confirmed"]+=1
        site=r.get("officialSite")
        if site and site!="不明": s["officialSite"]=site; stat["site"]+=1
        if r.get("category"):
            if r["category"]!=s.get("category"): stat["cat"]+=1
            s["category"]=r["category"]
        if r.get("address"):
            if r["address"]!=s.get("address"): stat["addr"]+=1; changed=True
            s["address"]=r["address"]
        if r.get("town"):
            s.setdefault("area",{})["town"]=r["town"]; changed=True
        if r.get("rating") and isinstance(r["rating"],dict) and r["rating"].get("score"):
            s["rating"]=r["rating"]
        if r.get("reviewComment"): s["reviewComment"]=r["reviewComment"]
        s["researchConfidence"]="確認済（再洗い）"
        if changed: s["googleMapsUrl"]=gmap(s.get("name"),s.get("address"))
        s["tags"]=derive_tags(s)
    else:
        stat["hearing"]+=1
        note=r.get("fixNote") or r.get("reviewComment") or ""
        if note: s["reviewComment"]=(s.get("reviewComment") or "")+" ／再洗い:"+note
        s["researchConfidence"]="要ヒアリング"

j["_meta"]["resweep"]="2026-06-06: 未解決50店を改良手法で再洗い。確認済=住所/業種/公式/評価を反映、要ヒアリングはフラグのみ。"
with open(SRC,"w",encoding="utf-8") as f: json.dump(j,f,ensure_ascii=False,indent=2)
print("stat:",stat)
