"""病院の広さ3つ（中小・中規模・大学）の、型の違う外来の階の図面を作る

サイトの試算（public/sim/service-robot-sites.html の病院のタブ）で、病院の広さを選ぶカードに出す図面。
3つの道（救急・病棟→検査部・内科外来→検査部・薬剤部→外来化学療法）の長さは、この図面の廊下の上で測る。
試算（iCloud の simulation_sites/hospital_sim.py）は、この長さをそのまま使う（倍率で伸ばさない）。

型は広さごとに変える（2026-11-20 エイイチと決めた）。どれも実在の病院ではなく、型をコードで起こした仮の病院。寸法はすべて仮置き。
- 中小（約200床・地域の病院）：1棟・廊下1本。科は内科・外科・整形外科くらい。検査室と薬局は廊下ぞいに固まる。
  外来化学療法は専用の部屋を持たず、内科外来の処置室の一角で行う。救急は時間外の入口と救急室だけ
- 中規模（約660床・地域の中核病院。慈恵医大柏病院の形）：1棟。大廊下（モール）にそって外来をブロックに分け（内科・外科・整形ほか）、
  ブロックの奥に職員の中廊下。大廊下の向かいに検査部・放射線・薬剤部、東の端に救急室と外来化学療法室
- 大学（約1,100床）：外来棟・中央診療棟・病棟の分棟を渡り廊下でつなぐ。検査部・薬剤部・救急は中央診療棟、
  外来化学療法室は外来棟。朝の検体は病棟から渡り廊下を通って検査部へ
距離：部屋の中の台の前から扉を出て、廊下の中心線の上を縦横だけで進み、届け先の台の前まで。いちばん短い道（同じ長さなら曲がる回数の少ない道）。
座標は m。x は西→東、y は南→北（正面の入口が下）。サイトの配膳の平面図（serving-robot.html の bigPlanSvg）と同じ向き。

使い方: python3 make_hospital_scales.py [出力フォルダ]   → hospital_scale_{small,mid,large}.json と hospital_scales.json
"""
import heapq
import json
import sys
from pathlib import Path

INSET = 2.0  # 台は扉のある壁から 2m 内側
P, ST, CO = "patient", "staff", "core"  # 部屋の種類：患者も入る所（白）・職員だけの所（灰）・エレベーター・階段（灰）


def build(key, label, beds, desc, style, buildings, bridges, corrs, rooms, stops, route_labels, ents):
    corrs = [list(c) for c in corrs] + [list(b) + ["bridge"] for b in bridges]

    # ---- 廊下の中心線（縦横の線分）
    raw = []
    for x0, y0, x1, y1, _ in corrs:
        raw.append(("h", (y0 + y1) / 2, x0, x1) if x1 - x0 >= y1 - y0 else ("v", (x0 + x1) / 2, y0, y1))
    hs = [l for l in raw if l[0] == "h"]
    vs = [l for l in raw if l[0] == "v"]
    TOL = 4.0  # 廊下どうしがつながる所で、中心線を相手の中心線まで届かせる
    lines = []
    for _, y, a, b in hs:
        xs = [x for _, x, c0, c1 in vs if c0 - TOL <= y <= c1 + TOL and a - TOL <= x <= b + TOL]
        lines.append(("h", y, min([a] + xs), max([b] + xs)))
    for _, x, a, b in vs:
        ys = [y for _, y, c0, c1 in hs if c0 - TOL <= x <= c1 + TOL and a - TOL <= y <= b + TOL]
        lines.append(("v", x, min([a] + ys), max([b] + ys)))

    def room(name):
        r = [r for r in rooms if r[5] == name]
        assert len(r) == 1, (key, name, len(r))
        return r[0]

    # ---- 台と、その扉の前の廊下の点
    pts = {}
    for sid, (name, side, f) in stops.items():
        x0, y0, x1, y1 = room(name)[:4]
        if side in ("top", "bottom"):
            p = (x0 + (x1 - x0) * f, y1 - INSET if side == "top" else y0 + INSET)
            cands = [l for l in lines if l[0] == "h" and l[2] - 1e-6 <= p[0] <= l[3] + 1e-6 and ((l[1] > p[1]) if side == "top" else (l[1] < p[1]))]
            l = min(cands, key=lambda l: abs(l[1] - p[1]))
            q = (p[0], l[1])
        else:
            p = (x1 - INSET if side == "right" else x0 + INSET, y0 + (y1 - y0) * f)
            cands = [l for l in lines if l[0] == "v" and l[2] - 1e-6 <= p[1] <= l[3] + 1e-6 and ((l[1] > p[0]) if side == "right" else (l[1] < p[0]))]
            l = min(cands, key=lambda l: abs(l[1] - p[0]))
            q = (l[1], p[1])
        pts[sid] = {"room": name, "at": [round(p[0], 2), round(p[1], 2)], "door": [round(q[0], 2), round(q[1], 2)]}

    # ---- 線の上の点（端・交わる所・扉の前）をつなぐ
    R = lambda p: (round(p[0], 3), round(p[1], 3))
    nodes = set()
    for o, c, a, b in lines:
        nodes |= {R((c, a) if o == "v" else (a, c)), R((c, b) if o == "v" else (b, c))}
    for o1, c1, a1, b1 in lines:
        for o2, c2, a2, b2 in lines:
            if o1 == "h" and o2 == "v" and a1 - 1e-6 <= c2 <= b1 + 1e-6 and a2 - 1e-6 <= c1 <= b2 + 1e-6:
                nodes.add(R((c2, c1)))
    for s in pts.values():
        nodes.add(R(s["door"]))
    adj = {n: [] for n in nodes}
    for o, c, a, b in lines:
        on = sorted([n for n in nodes if (abs(n[1] - c) < 1e-3 if o == "h" else abs(n[0] - c) < 1e-3)
                     and a - 1e-3 <= (n[0] if o == "h" else n[1]) <= b + 1e-3], key=lambda n: n[0] if o == "h" else n[1])
        for u, v in zip(on, on[1:]):
            d = abs(u[0] - v[0]) + abs(u[1] - v[1])
            adj[u].append((v, d))
            adj[v].append((u, d))

    def shortest(s, t):
        """いちばん短い道。同じ長さなら曲がる回数の少ない道（1回の曲がりを 0.5m 分として比べる。長さには足さない）"""
        s, t = R(s), R(t)
        start, cnt = (s, None), 0
        dist, prev, h, end = {start: 0.0}, {}, [(0.0, 0, start)], None
        while h:
            d, _, st = heapq.heappop(h)
            if st[0] == t:
                end = st
                break
            if d > dist[st]:
                continue
            for v, w in adj[st[0]]:
                nd = "h" if abs(v[1] - st[0][1]) < 1e-6 else "v"
                c = d + w + (0.5 if st[1] and nd != st[1] else 0)
                if c < dist.get((v, nd), 1e18):
                    dist[(v, nd)], prev[(v, nd)] = c, st
                    cnt += 1
                    heapq.heappush(h, (c, cnt, (v, nd)))
        assert end, (key, s, t)
        path = [end]
        while path[-1] != start:
            path.append(prev[path[-1]])
        return [p[0] for p in path[::-1]]

    def simplify(ps):
        out = [ps[0]]
        for p in ps[1:]:
            if p == out[-1]:
                continue
            if len(out) >= 2 and ((abs(out[-2][0] - out[-1][0]) < 1e-6 and abs(out[-1][0] - p[0]) < 1e-6)
                                  or (abs(out[-2][1] - out[-1][1]) < 1e-6 and abs(out[-1][1] - p[1]) < 1e-6)):
                out[-1] = p
            else:
                out.append(p)
        return out

    routes = {}
    for rid, (a, b) in {"r1": ("emer", "lab"), "r2": ("int", "lab"), "r3": ("pharm", "chemo")}.items():
        path = [tuple(pts[a]["at"])] + shortest(pts[a]["door"], pts[b]["door"]) + [tuple(pts[b]["at"])]
        path = simplify([(round(x, 2), round(y, 2)) for x, y in path])
        length = sum(abs(u[0] - v[0]) + abs(u[1] - v[1]) for u, v in zip(path, path[1:]))
        routes[rid] = {"label": route_labels[rid], "from": a, "to": b, "pts": [list(p) for p in path], "m": round(length)}

    W = max(b[2] for b in buildings)
    D = max(b[3] for b in buildings)
    return {
        "key": key, "label": label, "beds": beds, "desc": desc, "style": style, "w": W, "d": D,
        "floor_m2": round(sum((b[2] - b[0]) * (b[3] - b[1]) for b in buildings)),
        "buildings": buildings, "bridges": bridges, "rooms": rooms,
        "corridors": corrs, "ents": ents, "stops": pts, "routes": routes,
        "dist_m": {rid: r["m"] for rid, r in routes.items()},
    }


PLANS = [
    # 中小：1棟・廊下1本（3m）。化学療法は内科外来の処置室の一角
    build("small", "中小病院", 200, "地域の病院。科は内科・外科・整形外科くらい。化学療法は内科の処置室の一角",
          "1棟・廊下1本", buildings=[[0, 0, 72, 34]], bridges=[],
          corrs=[[0, 16, 72, 19, "main"]],
          rooms=[[0, 19, 22, 34, P, "内科外来"], [22, 19, 42, 34, P, "外科・整形外来"], [42, 19, 56, 34, ST, "検査室"], [56, 19, 72, 34, P, "放射線"],
                 [0, 0, 14, 16, P, "救急室"], [14, 0, 26, 16, ST, "薬局"], [26, 0, 50, 16, P, "受付・会計・待合"],
                 [50, 0, 58, 16, P, "玄関"], [58, 0, 72, 16, ST, "医事・事務"]],
          stops={"emer": ("救急室", "top", 0.5), "lab": ("検査室", "bottom", 0.5), "int": ("内科外来", "bottom", 0.8),
                 "pharm": ("薬局", "top", 0.5), "chemo": ("内科外来", "bottom", 0.25)},
          route_labels={"r1": "救急室 → 検査室", "r2": "内科外来 → 検査室", "r3": "薬局 → 内科の処置室（化学療法）"},
          ents=[[51.5, 0, 56.5, 0, "正面の入口"], [0, 4, 0, 10, "救急の入口"]]),
    # 中規模：1棟。大廊下（モール 6m）にそって外来のブロック、奥に職員の中廊下（2.1m）
    build("mid", "中規模病院", 660, "地域の中核病院。大廊下にそって外来をブロックに分ける。慈恵医大柏病院（664床）の形",
          "1棟・外来をブロックで分ける", buildings=[[0, 0, 175, 90]], bridges=[],
          corrs=[[0, 40, 175, 46, "main"], [0, 82, 150, 84.1, "staff"], [50, 46, 52.1, 82, "staff"], [100, 46, 102.1, 82, "staff"]],
          rooms=[[0, 46, 50, 82, P, "内科ブロック"], [52.1, 46, 100, 82, P, "外科ブロック"], [102.1, 46, 150, 82, P, "整形・ほかのブロック"],
                 [0, 84.1, 150, 90, ST, "職員の部屋・倉庫"], [150, 46, 175, 90, P, "外来化学療法室"],
                 [0, 0, 24, 40, ST, "薬剤部"], [24, 0, 38, 40, P, "お薬の窓口"], [38, 0, 74, 40, ST, "中央検査室"],
                 [74, 0, 100, 40, P, "放射線"], [100, 0, 130, 40, P, "総合受付・会計・待合"], [130, 0, 140, 40, P, "玄関"],
                 [140, 0, 175, 40, P, "救急室"]],
          stops={"emer": ("救急室", "top", 0.5), "lab": ("中央検査室", "top", 0.5), "int": ("内科ブロック", "top", 0.7),
                 "pharm": ("薬剤部", "top", 0.5), "chemo": ("外来化学療法室", "bottom", 0.4)},
          route_labels={"r1": "救急室 → 検査部", "r2": "内科ブロック → 検査部", "r3": "薬剤部 → 外来化学療法室"},
          ents=[[131.5, 0, 138.5, 0, "正面の入口"], [175, 10, 175, 24, "救急の入口"]]),
    # 大学：外来棟・中央診療棟・病棟を渡り廊下（4m）でつなぐ
    build("large", "大学病院", 1100, "外来棟・中央診療棟・病棟を渡り廊下でつなぐ。検査部・薬剤部・救急は中央診療棟",
          "分棟・渡り廊下でつなぐ", buildings=[[0, 0, 110, 70], [130, 0, 230, 80], [130, 110, 230, 150]],
          bridges=[[110, 31, 130, 35], [178, 80, 182, 110]],
          corrs=[[0, 30, 110, 36, "main"], [130, 30, 230, 36, "main"], [178, 36, 182, 80, "staff"],
                 [178, 110, 182, 124, "staff"], [130, 124, 230, 128, "main"]],
          rooms=[[0, 36, 40, 70, P, "内科外来"], [40, 36, 75, 70, P, "外科外来"], [75, 36, 110, 70, P, "外来化学療法室"],
                 [0, 0, 50, 30, P, "総合受付・会計・待合"], [50, 0, 62, 30, P, "玄関"], [62, 0, 80, 30, P, "お薬の窓口"],
                 [80, 0, 110, 30, ST, "医事・事務"],
                 [130, 0, 165, 30, P, "救急室"], [165, 0, 230, 30, P, "放射線"],
                 [130, 36, 178, 80, ST, "中央検査室"], [182, 36, 210, 80, ST, "薬剤部"], [210, 36, 230, 80, P, "内視鏡"],
                 [130, 110, 178, 124, P, "入退院の受付"], [182, 110, 230, 124, CO, "エレベーター・階段"],
                 [130, 128, 230, 150, P, "リハビリ"]],
          stops={"emer": ("エレベーター・階段", "top", 0.4), "lab": ("中央検査室", "bottom", 0.5), "int": ("内科外来", "bottom", 0.5),
                 "pharm": ("薬剤部", "bottom", 0.5), "chemo": ("外来化学療法室", "bottom", 0.5)},
          route_labels={"r1": "病棟 → 検査部", "r2": "内科外来 → 検査部", "r3": "薬剤部 → 外来化学療法室"},
          ents=[[51.5, 0, 60.5, 0, "正面の入口"], [138, 0, 157, 0, "救急の入口"]]),
]

if __name__ == "__main__":
    out = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    out.mkdir(parents=True, exist_ok=True)
    for p in PLANS:
        (out / f"hospital_scale_{p['key']}.json").write_text(json.dumps(p, ensure_ascii=False, indent=1), encoding="utf-8")
        print(p["key"], p["w"], "x", p["d"], p["floor_m2"], "m2", p["dist_m"])
    (out / "hospital_scales.json").write_text(json.dumps({p["key"]: p for p in PLANS}, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
