# -*- coding: utf-8 -*-
"""一次性补丁：把 17040 已在取的 taonei_users_ym 接进 daqu_parsed.json（套内用户数 + Q4 月末目标）"""
import io, sys
P = "/data/workspace/南部大区城市看板/refresh_convert.py"
s = io.open(P, encoding="utf-8").read()
orig = s

# 1) 城市循环前：读 targets.json 的套内目标块
a1 = "# ---------- cities（12直营，沿用旧城市清单与静态目标） ----------\ncities = {}"
n1 = """# ---------- cities（12直营，沿用旧城市清单与静态目标） ----------
# 套内用户数目标（2026-10-08 新增取数）：Q4 目标表「套内用户数_月末」→ targets.json
TGT_TN = TG.get("taonei_users") or {}
TGT_TN_CITY = TGT_TN.get("cities") or {}
cities = {}"""
assert s.count(a1) == 1, "anchor1 %d" % s.count(a1)
s = s.replace(a1, n1)

# 2) 城市字典：新增 套内用户 / 套内用户目标
a2 = """        "换电用户含单次": {"mtd": mget(m8, "huandian_hdc_users_ym"), "t1": None, "dod": None},"""
n2 = """        "换电用户含单次": {"mtd": mget(m8, "huandian_hdc_users_ym"), "t1": None, "dod": None},
        # 套内用户数（taonei_users_ym：日存量，月维=当月最后有数日）——原先只有静态手维值，10/8 起走实时取数
        "套内用户": {"mtd": mget(m8, "taonei_users_ym"), "t1": mget(d1, "taonei_users_ym"),
                   "dod": (mget(d1, "taonei_users_ym") - mget(d2, "taonei_users_ym")) if d1 and d2 else None},
        "套内用户目标": TGT_TN_CITY.get(c),"""
assert s.count(a2) == 1, "anchor2 %d" % s.count(a2)
s = s.replace(a2, n2)

# 3) 大区/直营/联营套内块（插在 award 段之前）
a3 = "# ---------- award（10/6 季度化："
n3 = """# ---------- 套内用户数（2026-10-08 新增取数：17040 本就在取 taonei_users_ym，此前未被消费） ----------
# 口径：taonei_users_ym = 套内用户数日存量，月维取值=当月最后有数日（非月累计/非日均）；
#       目标 = Q4 目标表「套内用户数_月末」。存量对月末目标，缺口为负属月中正常，展示用中性色。
def _tn(key, rows):
    rows = [r for r in rows if r]
    return sum(mget(r, key) or 0 for r in rows) if rows else None
_dm = [cm.get((c, M_MONTH)) for c in OLD["cities"]]
_d1 = [cd.get(c, {}).get(D1) for c in OLD["cities"]]
_lym = [x for x in city_m if x.get("city_type") == "联营" and str(x["data_date_mounth"]) == M_MONTH]
_ly1 = [cd[c][D1] for c in ly_cities if c in cd and D1 in cd[c]]
def _tnblk(mtd, t1, tgt):
    return {"mtd": mtd, "t1": t1, "target": tgt,
            "gap": (mtd - tgt) if mtd is not None and tgt is not None else None}
taonei = {
    "as_of": as_of,
    "source": "经营管理报表_核心指标（17040）· taonei_users_ym 日存量",
    "target_src": "《换电业务Q4经营目标分城市拆解》· 套内用户数_月末",
    "region": _tnblk(mget(r8, "taonei_users_ym"), mget(r1d, "taonei_users_ym"), TGT_TN.get("region")),
    "direct": _tnblk(_tn("taonei_users_ym", _dm), _tn("taonei_users_ym", _d1), TGT_TN.get("direct")),
    "lianying": _tnblk(_tn("taonei_users_ym", _lym), _tn("taonei_users_ym", _ly1), TGT_TN.get("lianying")),
    "cities": {c: {"mtd": cities[c]["套内用户"]["mtd"], "t1": cities[c]["套内用户"]["t1"],
                  "dod": cities[c]["套内用户"]["dod"], "target": cities[c]["套内用户目标"]} for c in cities},
}
_chk = sum((v["mtd"] or 0) for v in taonei["cities"].values())
_lychk = (_chk - (taonei["direct"]["mtd"] or 0))
print("套内用户校验：12直营Σ %.0f + 联营Σ %.0f = %.0f vs 大区 %.0f（差 %+.0f）" % (
    taonei["direct"]["mtd"] or 0, _lychk, _chk, taonei["region"]["mtd"] or 0,
    _chk - (taonei["region"]["mtd"] or 0)))

# ---------- award（10/6 季度化："""
assert s.count(a3) == 1, "anchor3 %d" % s.count(a3)
s = s.replace(a3, n3)

# 4) 输出：daqu_parsed.json 增加 taonei
a4 = """out = {"meta": meta, "region": region, "award": award, "cities": cities,"""
n4 = """out = {"meta": meta, "region": region, "award": award, "cities": cities, "taonei": taonei,"""
assert s.count(a4) == 1, "anchor4 %d" % s.count(a4)
s = s.replace(a4, n4)

io.open(P, "w", encoding="utf-8").write(s)
print("patched %s (+%d chars)" % (P, len(s) - len(orig)))