"""清掃ロボットの試算のフロアの形：オフィスビルの共用部・大型施設（空港の一角）（下書き）

商業施設（make_mall_floor.py の mall_m1）と同じ決まりで、残り2つの施設をコードで一から起こした仮の図面。実在の施設ではない。寸法はすべて仮置き。
- office_o1：オフィスビルの共用部。1階（エントランスホール・受付・セキュリティゲート・エレベーターホール）と、
  基準階（エレベーターホールとコアを回る廊下）を8階分。階の行き来はエレベーター（ロボットはエレベーターとつなぐ前提）
- large_a1：空港の出発ロビーの一角。チェックインカウンターの島・待合のベンチの列・柱・店（夜は閉店）

決まりは mall_m1 と同じ：壁の際0.8m・物のまわり0.5m・テーブルのまわり0.8m・マット・ロボットの体（幅0.6m）が入らない細い所は人の床、残りがロボットの床。
歩く距離は 0.5m の格子で床の上を8方向に。清掃員 1.1m/秒、ロボットが拭かずに移る 0.6m/秒、エレベーターの待ちと移動は片道1.0分（すべて仮置き）。

座標は m。x は西→東、y は南→北（正面の入口が下）。
使い方: python3 make_cleaning_floors.py [出力フォルダ]  → office_o1.json・large_a1.json と図
"""
import heapq
import json
import sys
from pathlib import Path

import numpy as np
from scipy import ndimage

RES = 0.1
EDGE_WALL, EDGE_OBJ, EDGE_TABLE, ROBOT_HALF = 0.8, 0.5, 0.8, 0.3
WALK, ROBOT_MOVE, EV_MIN = 1.1, 0.6, 1.0
C = 5  # 歩く距離の格子（0.5m）


def O(kind, label, x0, y0, x1, y1, snag):
    return {"kind": kind, "label": label, "rect": [round(float(x0), 2), round(float(y0), 2), round(float(x1), 2), round(float(y1), 2)], "snag": snag}


# ======================================================================== オフィス
def office():
    S2 = 70.0  # 基準階を描く位置（1階の右に並べる）
    floor, rooms, objs = [], [], []
    # ---- 1階：建物 60m×36m
    floor += [("エントランスホール", 18, 0, 42, 18), ("エレベーターホール（1階）", 24, 18, 36, 26),
              ("廊下（1階・東）", 36, 21, 54, 24), ("廊下（1階・西）", 6, 21, 24, 24), ("通用口の通路", 51, 24, 54, 34)]
    rooms += [("テナント（店）", 0, 0, 18, 21), ("テナント（店）", 42, 0, 60, 21), ("エレベーター", 26, 26, 34, 29),
              ("トイレ", 18, 24, 24, 33), ("トイレ", 36, 24, 42, 33), ("防災センター", 6, 24, 18, 36),
              ("清掃員の控室（給排水・充電台）", 42, 26, 51, 34), ("テナント（事務所）", 0, 21, 6, 36),
              ("バックヤード", 18, 33, 51, 36), ("機械室", 54, 21, 60, 36)]
    objs += [O("counter", "受付カウンター", 34, 13, 40, 14.2, ""),
             O("gate", "セキュリティゲート", 24, 16.6, 25.2, 17.4, "ゲートの脚"), O("gate", "セキュリティゲート", 27, 16.6, 28.2, 17.4, "ゲートの脚"),
             O("gate", "セキュリティゲート", 31.8, 16.6, 33, 17.4, "ゲートの脚"), O("gate", "セキュリティゲート", 34.8, 16.6, 36, 17.4, "ゲートの脚"),
             O("sofa", "ソファ", 20, 8, 22.2, 12, "ソファの脚"), O("sofa", "ソファ", 20, 13, 22.2, 15.5, "ソファの脚"),
             O("planter", "植栽", 39.5, 3, 41, 4.5, "植栽の縁"), O("planter", "植栽", 19, 3, 20.5, 4.5, "植栽の縁"),
             O("column", "柱", 23.6, 8.6, 24.4, 9.4, ""), O("column", "柱", 35.6, 8.6, 36.4, 9.4, ""),
             O("sign", "案内板", 29.7, 19, 30.3, 19.6, "台座")]
    mats = [("マット", 25, 0.5, 35, 4.5), ("マット", 51.5, 31, 53.5, 33.5)]
    # ---- 基準階：外形は同じ 60m×36m。コア（エレベーター・トイレ・階段）を廊下が回る。事務所は扉の外（拭かない）
    X = lambda a: a + S2
    floor += [("エレベーターホール（基準階）", X(24), 14, X(36), 22),
              ("廊下（基準階・南）", X(13.7), 11.2, X(46.3), 14), ("廊下（基準階・北）", X(13.7), 22, X(46.3), 24.8),
              ("廊下（基準階・西）", X(13.7), 14, X(16.5), 22), ("廊下（基準階・東）", X(43.5), 14, X(46.3), 22)]
    rooms += [("事務所（夜は施錠）", X(0), 0, X(60), 11.2), ("事務所（夜は施錠）", X(0), 24.8, X(60), 36),
              ("事務所（夜は施錠）", X(0), 11.2, X(13.7), 24.8), ("事務所（夜は施錠）", X(46.3), 11.2, X(60), 24.8),
              ("トイレ", X(16.5), 14, X(24), 22), ("トイレ・階段", X(36), 14, X(43.5), 22), ("エレベーター", X(26), 19.5, X(34), 22)]
    objs += [O("sign", "案内板", X(29.7), 15, X(30.3), 15.6, "台座"),
             O("box", "消火器", X(13.8), 18, X(14.2), 18.4, "台座"), O("box", "消火器", X(45.8), 18, X(46.2), 18.4, "台座"),
             O("trash", "ごみ箱", X(35.2), 21, X(35.8), 21.5, "")]
    sheets = [{"name": "1階", "x0": 0, "x1": 60, "ev": (30, 25.5), "mult": 1},
              {"name": "基準階（2〜9階）", "x0": S2, "x1": S2 + 60, "ev": (X(30), 18.5), "mult": 8}]
    patrol = [(46, 26), (46, 22.5), (8, 22.5), (30, 22.5), (30, 2), (30, 22.5), (46, 22.5), (46, 26)]
    return {"key": "office_o1", "label": "オフィスビルの共用部（仮）", "w": S2 + 60, "d": 36.0,
            "note": "実在のビルではない。都市部の中規模オフィスビルの1階と基準階の典型の並びをコードで起こした仮の図面。基準階は8階分。寸法はすべて仮置き",
            "floor": floor, "rooms": rooms, "objects": objs, "mats": mats, "door": (46.5, 26), "dock": (46.5, 25.2),
            "patrol": patrol, "sheets": sheets}


# ======================================================================== 大型施設（空港の出発ロビーの一角）
def large():
    W, D = 170.0, 80.0
    floor = [("出発ロビー", 0, 8, 170, 68), ("入口の風除室", 20, 0, 40, 8), ("入口の風除室", 75, 0, 95, 8),
             ("入口の風除室", 130, 0, 150, 8), ("控室の通路", 160, 68, 163, 74)]
    rooms = [("店（夜は閉店）", 0, 68, 30, 80), ("店（夜は閉店）", 30, 68, 60, 80), ("保安検査場（夜は閉鎖）", 60, 68, 110, 80),
             ("店（夜は閉店）", 110, 68, 135, 80), ("トイレ", 135, 68, 147, 80), ("トイレ", 147, 68, 159, 80),
             ("清掃員の控室（給排水・充電台）", 159, 74, 170, 80)]
    objs = []
    # 柱：18m おき
    for cx in np.arange(9.0, 170, 18):
        for cy in (22.0, 52.0):
            objs.append(O("column", "柱", cx - 0.6, cy - 0.6, cx + 0.6, cy + 0.6, ""))
    # チェックインカウンターの島（3つ）と、並ぶ所のベルトパーテーション（ポールの台座）
    for x0 in (22.0, 70.0, 118.0):
        objs.append(O("counter", "チェックインカウンター", x0, 40, x0 + 30, 44, ""))
        for px in np.arange(x0, x0 + 30.1, 3.0):
            for py in (34.0, 37.0, 47.0, 50.0):
                objs.append(O("pole", "ベルトパーテーションのポール", px - 0.15, py - 0.15, px + 0.15, py + 0.15, "ポールの台座"))
    # 待合のベンチの列（窓ぎわ・南）
    for bx in np.arange(4.0, 166, 14.0):
        if any(a - 2 < bx + 10 and bx < b + 2 for a, b in ((20, 40), (75, 95), (130, 150))):
            continue
        for by in (12.0, 15.5):
            objs.append(O("bench", "待合のベンチ", bx, by, bx + 10, by + 0.6, "ベンチの脚"))
    # 案内板・ごみ箱・カートの置き場
    for sx in (10.0, 60.0, 112.0, 160.0):
        objs.append(O("sign", "案内板", sx - 0.4, 28.6, sx + 0.4, 29.4, "台座"))
    for tx in (45.0, 100.0, 152.0):
        objs.append(O("trash", "ごみ箱", tx, 64, tx + 1.2, 64.6, ""))
    objs.append(O("cart", "カートの置き場", 4, 30, 8, 36, "カートの車輪止め"))
    objs.append(O("cart", "カートの置き場", 162, 30, 166, 36, "カートの車輪止め"))
    mats = [("マット", 21, 0.5, 39, 4.5), ("マット", 76, 0.5, 94, 4.5), ("マット", 131, 0.5, 149, 4.5)]
    patrol = [(161.5, 74), (161.5, 60), (5, 60), (5, 20), (165, 20), (165, 60), (161.5, 60), (161.5, 74)]
    return {"key": "large_a1", "label": "大型施設（空港の出発ロビーの一角・仮）", "w": W, "d": D,
            "note": "実在の空港ではない。出発ロビーの一角の典型の並び（チェックインカウンターの島・待合のベンチ・柱・店）をコードで起こした仮の図面。寸法はすべて仮置き",
            "floor": floor, "rooms": rooms, "objects": objs, "mats": mats, "door": (161.5, 74), "dock": (161.5, 73.2),
            "patrol": patrol, "sheets": [{"name": "出発ロビー", "x0": 0, "x1": W, "ev": None, "mult": 1}]}


# ======================================================================== 共通の計算
def mask(shape, rects):
    m = np.zeros(shape, bool)
    for r in rects:
        x0, y0, x1, y1 = r[-4:]
        m[int(round(y0 / RES)):int(round(y1 / RES)), int(round(x0 / RES)):int(round(x1 / RES))] = True
    return m


def build(sp):
    shape = (int(round(sp["d"] / RES)), int(round(sp["w"] / RES)))
    floor = mask(shape, sp["floor"]) & ~mask(shape, sp["rooms"])
    objs = mask(shape, [o["rect"] for o in sp["objects"]])
    tables = mask(shape, [o["rect"] for o in sp["objects"] if o["kind"] == "table"])
    mats = mask(shape, sp["mats"]) & floor
    floor_net = floor & ~objs
    d_wall = ndimage.distance_transform_edt(floor) * RES
    d_obj = ndimage.distance_transform_edt(~objs) * RES
    d_tab = ndimage.distance_transform_edt(~tables) * RES
    cand = floor_net & ~mats & (d_wall >= EDGE_WALL) & (d_obj >= EDGE_OBJ) & (d_tab >= EDGE_TABLE)
    r = int(round(ROBOT_HALF / RES))
    yy, xx = np.mgrid[-r:r + 1, -r:r + 1]
    robot = ndimage.binary_opening(cand, structure=xx ** 2 + yy ** 2 <= r * r)
    people = floor_net & ~robot

    # 階ごとの重み（基準階は何階分か）
    weight = np.ones(shape)
    sheet_of = np.zeros(shape, int)
    for i, s in enumerate(sp["sheets"]):
        a, b = int(round(s["x0"] / RES)), int(round(s["x1"] / RES))
        weight[:, a:b] = s["mult"]
        sheet_of[:, a:b] = i
    area = lambda m: float((m * weight).sum() * RES * RES)

    # ---- 歩く距離（0.5m の格子）。階をまたぐときはエレベーターの前まで歩き、エレベーターの分（EV_MIN）を足す
    walk = floor[::C, ::C] & ~objs[::C, ::C]
    h, w = walk.shape
    steps = [(dy, dx, (dy * dy + dx * dx) ** 0.5) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dy or dx]

    def geo(pt):
        sx, sy = min(int(pt[0] / (RES * C)), w - 1), min(int(pt[1] / (RES * C)), h - 1)
        if not walk[sy, sx]:  # 扉の点が床の外なら、近い床の点から
            ys, xs = np.nonzero(walk)
            k = np.argmin((ys - sy) ** 2 + (xs - sx) ** 2)
            sy, sx = ys[k], xs[k]
        dist = np.full((h, w), np.inf)
        dist[sy, sx] = 0
        q = [(0.0, sy, sx)]
        while q:
            d, y, x = heapq.heappop(q)
            if d > dist[y, x]:
                continue
            for dy, dx, c in steps:
                ny, nx = y + dy, x + dx
                if 0 <= ny < h and 0 <= nx < w and walk[ny, nx] and d + c < dist[ny, nx]:
                    dist[ny, nx] = d + c
                    heapq.heappush(q, (d + c, ny, nx))
        return dist * RES * C

    sh = sheet_of[::C, ::C]
    wt = weight[::C, ::C]
    home = 0  # 控室のある階（1枚目）
    g_door = geo(sp["door"])
    g_ev = {i: geo(s["ev"]) for i, s in enumerate(sp["sheets"]) if s["ev"]}

    def to_door(cells):
        """控室の扉から、各点までの (歩く m, エレベーターの分)"""
        out = []
        for y, x in cells:
            i = sh[y, x]
            if i == home:
                out.append((g_door[y, x], 0.0))
            else:
                ev_home = g_door[int(sp["sheets"][home]["ev"][1] / (RES * C)), int(sp["sheets"][home]["ev"][0] / (RES * C))]
                out.append((g_ev[i][y, x] + ev_home, EV_MIN))
        return out

    rb_cells = np.argwhere(robot[::C, ::C] & walk)
    rw = wt[rb_cells[:, 0], rb_cells[:, 1]]
    td = to_door(rb_cells)

    def wpct(vals, weights, qs):
        o = np.argsort(vals)
        v, cw = np.array(vals)[o], np.cumsum(np.array(weights)[o])
        return [float(v[np.searchsorted(cw, q / 100 * cw[-1])]) for q in qs]

    walk_m = [d for d, _ in td]
    ev_min = [e for _, e in td]
    t_room = [d / WALK / 60 + e for d, e in td]
    t_trip = [2 * (d / ROBOT_MOVE / 60 + e) for d, e in td]
    # 人の床のどこか（12か所・階の重みで選ぶ）からロボットの床のどこかまで
    rng = np.random.default_rng(0)
    pc = np.argwhere(people[::C, ::C] & walk)
    pw = wt[pc[:, 0], pc[:, 1]]
    pick = pc[rng.choice(len(pc), 12, replace=False, p=pw / pw.sum())]
    tb, tbw = [], []
    for y, x in pick:
        i = sh[y, x]
        g = geo(((x + 0.5) * RES * C, (y + 0.5) * RES * C))
        for (ry, rx), ww in zip(rb_cells, rw):
            j = sh[ry, rx]
            if i == j:
                tb.append(g[ry, rx] / WALK / 60)
            else:  # 別の階：自分の階のエレベーターまで＋エレベーター＋相手の階のエレベーターから
                gi = g_ev[i][y, x]
                tb.append((gi + g_ev[j][ry, rx]) / WALK / 60 + EV_MIN)
            tbw.append(ww)
    q3 = (10, 50, 90)
    A = {"floor": round(area(floor_net)), "robot": round(area(robot)), "people": round(area(people)), "mats": round(area(mats))}
    out = {k: sp[k] for k in ("key", "label", "w", "d", "note")}
    out.update({
        "floor": [list(f) for f in sp["floor"]], "rooms": [list(r_) for r_ in sp["rooms"]], "objects": sp["objects"],
        "mats": [list(m) for m in sp["mats"]], "control_room_door": list(sp["door"]), "dock": list(sp["dock"]),
        "patrol": [list(p) for p in sp["patrol"]],
        "sheets": [{"name": s["name"], "x0": s["x0"], "x1": s["x1"], "ev": list(s["ev"]) if s["ev"] else None, "mult": s["mult"]} for s in sp["sheets"]],
        "rules": {"edge_wall_m": EDGE_WALL, "edge_obj_m": EDGE_OBJ, "edge_table_m": EDGE_TABLE, "robot_half_width_m": ROBOT_HALF,
                  "walk_mps": WALK, "robot_move_mps": ROBOT_MOVE, "elevator_min_one_way": EV_MIN},
        "area_m2": A, "share": round(A["robot"] / A["floor"], 3),
        "walk_to_robot": {"m_p10_p50_p90": [round(v) for v in wpct(walk_m, rw, q3)], "min": [round(v, 1) for v in wpct(t_room, rw, q3)],
                          "note": "控室からロボットの床のどこかまで（別の階はエレベーターの分を足す）"},
        "walk_between": {"min": [round(v, 1) for v in wpct(tb, tbw, q3)], "note": "人の床のどこか（12か所）からロボットの床のどこかまで"},
        "dock_trip": {"min": [round(v, 1) for v in wpct(t_trip, rw, q3)], "note": "ロボットが控室まで行って戻る"},
        "unreachable_robot_cells": int((robot[::C, ::C] & walk & ~np.isfinite(g_door)).sum()) if len(sp["sheets"]) == 1 else 0,
        "snag_objects": {k: sum(1 for o in sp["objects"] if o["snag"] == k) for k in sorted({o["snag"] for o in sp["objects"] if o["snag"]})} | {"マットの端": len(sp["mats"])},
    })
    return out, floor, objs, mats, robot, people


def draw(sp, out, floor, objs, mats, robot, people, folder):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    plt.rcParams["font.family"] = "Noto Sans CJK JP"
    INK, GRAY, LINE, BLUE = "#242424", "#d9d9d9", "#8c8c8c", "#2f6fdf"
    W, D = sp["w"], sp["d"]
    for kind in ("plan", "robot_floor"):
        fig, ax = plt.subplots(figsize=(16, 16 * (D + 10) / (W + 4)), dpi=110)
        for s in sp["sheets"]:
            ax.add_patch(Rectangle((s["x0"], 0), s["x1"] - s["x0"], D, facecolor="#efefef", edgecolor=INK, lw=1.2))
            ax.text((s["x0"] + s["x1"]) / 2, D + 1.2, s["name"], ha="center", fontsize=11, color=INK)
        for f in sp["floor"]:
            ax.add_patch(Rectangle(f[1:3], f[3] - f[1], f[4] - f[2], facecolor="white", edgecolor="none"))
        for r in sp["rooms"]:
            ax.add_patch(Rectangle(r[1:3], r[3] - r[1], r[4] - r[2], facecolor=GRAY, edgecolor=LINE, lw=0.6))
            ax.text((r[1] + r[3]) / 2, (r[2] + r[4]) / 2, r[0].replace("清掃員の控室（給排水・充電台）", "控室"), ha="center", va="center", fontsize=8, color=INK)
        if kind == "plan":
            for o in sp["objects"]:
                x0, y0, x1, y1 = o["rect"]
                ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor="#9aa59a" if o["kind"] == "planter" else "#6b6b6b", edgecolor="none"))
            for m in sp["mats"]:
                ax.add_patch(Rectangle(m[1:3], m[3] - m[1], m[4] - m[2], facecolor="none", edgecolor=LINE, hatch="////", lw=0.6))
            px, py = zip(*sp["patrol"])
            ax.plot(px, py, color=INK, lw=0.8, ls=(0, (4, 3)), alpha=0.55)
            cap = "■ 充電台・給排水（控室）   ／／ マット   ‐‐ 警備員の巡回   清掃する床 約{:,}㎡".format(out["area_m2"]["floor"])
        else:
            img = np.zeros(floor.shape + (4,))
            img[people] = matplotlib.colors.to_rgba("#a6a6a6", 0.9)
            img[mats] = matplotlib.colors.to_rgba("#6b6b6b", 0.9)
            img[robot] = matplotlib.colors.to_rgba(BLUE, 0.55)
            img[objs] = matplotlib.colors.to_rgba(INK, 1)
            ax.imshow(img, origin="lower", extent=(0, W, 0, D), interpolation="nearest", zorder=3)
            a = out["area_m2"]
            cap = "青：ロボットの床 {:,}㎡（{:.0%}）   灰：人の床 {:,}㎡   濃い灰：マット".format(a["robot"], out["share"], a["people"] - a["mats"])
        for f in sp["floor"]:
            if f[3] - f[1] > 8 and f[4] - f[2] > 6:
                ax.text((f[1] + f[3]) / 2, (f[2] + f[4]) / 2, f[0], ha="center", va="center", fontsize=9, color=INK, zorder=5)
        ax.plot([sp["dock"][0]], [sp["dock"][1]], marker="s", ms=7, color=BLUE, zorder=6)
        ax.text(0, -3, cap, fontsize=10, color=INK, va="center")
        ax.set_xlim(-2, W + 2)
        ax.set_ylim(-6, D + 3)
        ax.set_aspect("equal")
        ax.axis("off")
        fig.tight_layout()
        fig.savefig(folder / f"{sp['key']}_{kind}.png")
        plt.close(fig)


if __name__ == "__main__":
    folder = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    folder.mkdir(parents=True, exist_ok=True)
    for sp in (office(), large()):
        out, *ms = build(sp)
        (folder / f"{sp['key']}.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
        draw(sp, out, *ms, folder)
        print(sp["key"], json.dumps({k: out[k] for k in ("area_m2", "share", "walk_to_robot", "walk_between", "dock_trip", "unreachable_robot_cells", "snag_objects")}, ensure_ascii=False))
