# -*- coding: utf-8 -*-
# 名店マスターに googleMapsUrl・tags・officialSite/rating/reviewComment 枠を付与する。
# 既存値は保持。公式サイト/評価は調査前は null（ビューアで「不明」表示）。
import json, os, urllib.parse

HERE = os.path.dirname(os.path.abspath(__file__))
SRC  = os.path.join(HERE, "meiten-master.json")

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

LBLGROUP = {
    "L1a":"継続広告主","L1b":"継続広告主","L1c":"継続広告主","L1d":"継続広告主",
    "L2":"途絶★再コンタクト","L3":"埋蔵金(取材済未広告)","L4":"グループ内",
    "L5":"域外/大手","L6":"未接触/新規開拓",
}

def gmap(name, address):
    q = (name or "") + " " + (address or "")
    return "https://www.google.com/maps/search/?api=1&query=" + urllib.parse.quote(q.strip())

def derive_tags(s):
    t = []
    g = LBLGROUP.get(s.get("label"))
    if g: t.append(g)
    ward = (s.get("area") or {}).get("ward")
    if ward: t.append(ward)
    town = (s.get("area") or {}).get("town")
    if town: t.append(town)
    for piece in (s.get("category") or "").replace("／","・").split("・"):
        piece = piece.strip()
        if piece and piece not in t: t.append(piece)
    issues = s.get("issuesPlaced") or []
    if 15 in issues: t.append("Vol.15出稿")
    if s.get("lapsed"): t.append("途絶")
    tg = (s.get("tegataFit") or {}).get("level")
    if tg == "高": t.append("手形適性高")
    if s.get("hotelEastFit") == "高": t.append("ホテル送客高")
    if s.get("potentialTier"): t.append("ポテンシャル"+s["potentialTier"])
    # dedupe preserve order
    seen=set(); out=[]
    for x in t:
        if x not in seen: seen.add(x); out.append(x)
    return out

n=0
for s in j.get("stores", []):
    s["googleMapsUrl"] = gmap(s.get("name"), s.get("address"))
    s.setdefault("officialSite", None)        # 調査で埋める／無ければ "不明"
    s.setdefault("rating", None)              # 例 {"source":"食べログ","score":"3.5","url":"..."}
    s.setdefault("reviewComment", None)       # 短評（出典つき）／不明
    s["tags"] = derive_tags(s)
    n+=1

j["_meta"]["enriched"] = "2026-06-06: googleMapsUrl/tags付与、officialSite/rating/reviewCommentは調査待ち枠"
with open(SRC, "w", encoding="utf-8") as f:
    json.dump(j, f, ensure_ascii=False, indent=2)

print("enriched stores:", n)
print("sample tags:", j["stores"][1]["name"], "->", j["stores"][1]["tags"])
print("sample map:", j["stores"][1]["googleMapsUrl"][:80])
