"""ファミレスの店の形を作り、ロボットが各卓へ届くかを測って、上から見た図にする。

使い方:
    python3 famires_gen.py            # 5パターンを作って、ベース（v11）と一緒に測って描く

単位はメートル。原点は左下、x が右、y が上。
ロボットの幅（RobotRadius×2）と卓の間の通路幅（gap）は仮の値。
"""
import heapq
import json
import math
from pathlib import Path

import numpy as np
from scipy.ndimage import binary_dilation

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle, Polygon

plt.rcParams["font.family"] = "Noto Sans CJK JP"

HERE = Path(__file__).parent
RES = 0.1            # 計算のマス目（m）
ROBOT_RADIUS = 0.35  # ロボットの半径（仮）。通れる最小の通路幅は約0.7m
REACH = 0.8          # 卓の縁からこの距離以内に止まれれば「届く」とする

INK, MUTED, BACK, SEAT = "#1f2328", "#8a9099", "#eceef1", "#ffffff"
ROBOT, DRINK, DISH, NG = "#e8590c", "#1c7ed6", "#2f9e44", "#e03131"


# ---------------------------------------------------------------- 形の部品
def footprint(t):
    """卓が床を占める範囲（矩形）"""
    typ = t["type"]
    if typ == "t4":
        return (t["x"] - 0.6, t["y"] - 0.6, t["x"] + 0.6, t["y"] + 0.6)
    if typ == "r4":
        return (t["x"] - 0.55, t["y"] - 0.55, t["x"] + 0.55, t["y"] + 0.55)
    if typ == "long6":
        return (t["x"] - 1.6, t["y"] - 0.97, t["x"] + 1.6, t["y"] + 0.97)
    return (t["x"], t["y"], t["x"] + t["w"], t["y"] + t["h"])


def overlap(a, b, pad=0.0):
    return not (a[2] + pad <= b[0] or b[2] + pad <= a[0] or a[3] + pad <= b[1] or b[3] + pad <= a[1])


def inside(r, region):
    return r[0] >= region[0] - 1e-6 and r[1] >= region[1] - 1e-6 and r[2] <= region[2] + 1e-6 and r[3] <= region[3] + 1e-6


def wall_booths(side, a0, a1, wall=0.0, pitch=1.9, depth=1.3, zone=""):
    """壁ぞいに4人掛けのボックス席（テーブルの端が壁に付く形）を並べる"""
    out = []
    n = int((a1 - a0) // pitch)
    for i in range(n):
        s = a0 + i * pitch
        if side == "left":
            r = dict(x=wall, y=s, w=depth, h=pitch)
        elif side == "right":
            r = dict(x=wall - depth, y=s, w=depth, h=pitch)
        elif side == "top":
            r = dict(x=s, y=wall - depth, w=pitch, h=depth)
        else:  # bottom
            r = dict(x=s, y=wall, w=pitch, h=depth)
        out.append(dict(type="booth4", side=side, seats=4, zone=zone, **r))
    return out


def fill_tables(regions, blocked, gap, zone="", start_offset=None):
    """空いている所に4人席を格子状に置く。卓どうし・障害物との間は gap 以上あける"""
    pitch = 1.2 + gap
    placed = []
    for reg in regions:
        x0, y0, x1, y1 = reg
        ox = x0 + gap + 0.6 if start_offset is None else x0 + start_offset
        y = y1 - gap - 0.6
        while y - 0.6 >= y0:
            x = ox
            while x + 0.6 <= x1:
                fp = (x - 0.6, y - 0.6, x + 0.6, y + 0.6)
                if inside(fp, reg) and not any(overlap(fp, b, gap) for b in blocked + [footprint(p) for p in placed]):
                    placed.append(dict(type="t4", x=round(x, 2), y=round(y, 2), seats=4, zone=zone))
                    x += pitch
                else:
                    x += 0.1
            y -= pitch
    return placed


# ---------------------------------------------------------------- ロボットが届くか
def analyze(L):
    W, D = L["outer"]["w"], L["outer"]["d"]
    nx, ny = int(round(W / RES)), int(round(D / RES))
    occ = np.zeros((ny, nx), bool)
    occ[0, :] = occ[-1, :] = occ[:, 0] = occ[:, -1] = True

    def block(r):
        x0, y0, x1, y1 = r
        occ[max(0, int(y0 / RES)):min(ny, int(math.ceil(y1 / RES))),
            max(0, int(x0 / RES)):min(nx, int(math.ceil(x1 / RES)))] = True

    for r in L["rooms"]:
        block(r["rect"])
    for w in L["walls"]:
        block(w["rect"])
    for t in L["tables"]:
        block(footprint(t))

    k = int(math.ceil(ROBOT_RADIUS / RES))
    yy, xx = np.mgrid[-k:k + 1, -k:k + 1]
    blocked = binary_dilation(occ, structure=(xx ** 2 + yy ** 2) <= k * k)

    sx, sy = L["start"]
    s = (int(sy / RES), int(sx / RES))
    dist = np.full((ny, nx), np.inf)
    parent = {}
    if not blocked[s]:
        dist[s] = 0
        pq = [(0.0, s)]
        steps = [(dy, dx, math.hypot(dy, dx) * RES) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dy or dx]
        while pq:
            d, (cy, cx) = heapq.heappop(pq)
            if d > dist[cy, cx]:
                continue
            for dy, dx, c in steps:
                py, px = cy + dy, cx + dx
                if 0 <= py < ny and 0 <= px < nx and not blocked[py, px] and d + c < dist[py, px]:
                    dist[py, px] = d + c
                    parent[(py, px)] = (cy, cx)
                    heapq.heappush(pq, (d + c, (py, px)))

    results = []
    for t in L["tables"]:
        x0, y0, x1, y1 = footprint(t)
        gx0, gx1 = max(0, int((x0 - REACH) / RES)), min(nx, int(math.ceil((x1 + REACH) / RES)))
        gy0, gy1 = max(0, int((y0 - REACH) / RES)), min(ny, int(math.ceil((y1 + REACH) / RES)))
        sub = dist[gy0:gy1, gx0:gx1]
        if not np.isfinite(sub).any():
            results.append(dict(reach=False))
            continue
        iy, ix = np.unravel_index(np.argmin(sub), sub.shape)
        cell = (gy0 + iy, gx0 + ix)
        path = [cell]
        while path[-1] in parent:
            path.append(parent[path[-1]])
        pts = [((c[1] + 0.5) * RES, (c[0] + 0.5) * RES) for c in reversed(path)][::3]
        results.append(dict(reach=True, dist=round(float(dist[cell]), 1), path=pts))

    reach = [r for r in results if r["reach"]]
    seats = sum(t["seats"] for t in L["tables"])
    stats = dict(
        seats=seats,
        tables=len(L["tables"]),
        reachable=len(reach),
        unreachable_seats=sum(t["seats"] for t, r in zip(L["tables"], results) if not r["reach"]),
        mean_dist=round(sum(r["dist"] for r in reach) / len(reach), 1) if reach else None,
        max_dist=max((r["dist"] for r in reach), default=None),
    )
    return results, stats


# ---------------------------------------------------------------- 描く
def draw_table(ax, t, ng=False):
    ec = NG if ng else INK
    typ, x, y = t["type"], t["x"], t["y"]
    lab = str(t["seats"])
    if typ == "t4":
        ax.add_patch(Rectangle((x - 0.6, y - 0.6), 1.2, 1.2, fc=SEAT, ec=ec, lw=1.2, zorder=3))
        ax.text(x, y, lab, ha="center", va="center", fontsize=9, color=ec, zorder=5)
    elif typ == "r4":
        ax.add_patch(Circle((x, y), 0.55, fc=SEAT, ec=ec, lw=1.2, zorder=3))
        ax.text(x, y, lab, ha="center", va="center", fontsize=9, color=ec, zorder=5)
    elif typ == "long6":
        ax.add_patch(Rectangle((x - 1.6, y - 0.35), 3.2, 0.7, fc=SEAT, ec=ec, lw=1.2, zorder=3))
        for dx in (-1.0, 0.0, 1.0):
            for dy in (-0.75, 0.75):
                ax.add_patch(Circle((x + dx, y + dy), 0.22, fc=SEAT, ec=ec, lw=1, zorder=3))
        ax.text(x, y, lab, ha="center", va="center", fontsize=8, color=ec, zorder=5)
    elif typ == "booth4":
        w, h, side = t["w"], t["h"], t["side"]
        ax.add_patch(Rectangle((x, y), w, h, fc=SEAT, ec=ec, lw=1.0, zorder=3))
        if side in ("left", "right"):   # ベンチが上下、テーブルが真ん中
            for by in (y, y + h - 0.55):
                ax.add_patch(Rectangle((x, by), w, 0.55, fc="#dee2e6", ec=ec, lw=0.8, zorder=3))
        else:
            for bx in (x, x + w - 0.55):
                ax.add_patch(Rectangle((bx, y), 0.55, h, fc="#dee2e6", ec=ec, lw=0.8, zorder=3))
        ax.text(x + w / 2, y + h / 2, lab, ha="center", va="center", fontsize=8, color=ec, zorder=5)
    elif typ == "booth6L":
        w, h = t["w"], t["h"]
        pts = [(x, y), (x + w, y), (x + w, y + h * 0.45), (x + w * 0.55, y + h * 0.45), (x + w * 0.55, y + h), (x, y + h)]
        ly, lx = y + h * 0.4, x + w * 0.3
        if t.get("flip"):
            pts = [(px, 2 * y + h - py) for px, py in pts]
            ly = y + h * 0.6
        if t.get("mirror"):
            pts = [(2 * x + w - px, py) for px, py in pts]
            lx = x + w * 0.7
        ax.add_patch(Polygon(pts, closed=True, fc=SEAT, ec=ec, lw=1.2, zorder=3))
        ax.text(lx, ly, lab, ha="center", va="center", fontsize=9, color=ec, zorder=5)


def draw(ax, L, results, stats, small=False):
    W, D = L["outer"]["w"], L["outer"]["d"]
    fs = 7 if small else 9
    ax.set_xlim(-0.8, W + 0.8)
    ax.set_ylim(-1.6 if not small else -1.2, D + 0.6)
    ax.set_aspect("equal")
    ax.axis("off")

    e0, e1 = L["entrance"]["x0"], L["entrance"]["x1"]
    lw = 2.2 if small else 3
    ax.plot([0, e0], [0, 0], color=INK, lw=lw)
    ax.plot([e1, W], [0, 0], color=INK, lw=lw)
    ax.plot([0, 0, W, W], [0, D, D, 0], color=INK, lw=lw)
    ax.text((e0 + e1) / 2, -0.45, "入口", ha="center", va="center", fontsize=fs, weight="bold")

    for r in L["rooms"]:
        fc = {"back": BACK, "guest": "#f8f9fa", "drink": "#d0ebff"}[r["kind"]]
        ec = DRINK if r["kind"] == "drink" else INK
        x0, y0, x1, y1 = r["rect"]
        ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc=fc, ec=ec, lw=1.0, zorder=2))
        tall = (y1 - y0) > (x1 - x0) * 1.6
        text = "\n".join(r["label"]) if tall and len(r["label"]) <= 5 else r["label"]
        size = fs - 1 if len(r["label"]) > 5 else fs
        ax.text((x0 + x1) / 2, (y0 + y1) / 2, text, ha="center", va="center", fontsize=size,
                color=DRINK if r["kind"] == "drink" else INK, zorder=5)
    for w in L["walls"]:
        x0, y0, x1, y1 = w["rect"]
        ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="#adb5bd", ec=INK, lw=0.6, hatch="////", zorder=3))
    for d in L["dish_up"]:
        x0, y0, x1, y1 = d["rect"]
        ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc=DISH, ec=DISH, zorder=4))

    # ロボットの道（受け渡し口から各卓まで、一番短い道）
    for r in results:
        if r["reach"]:
            xs, ys = zip(*r["path"])
            ax.plot(xs, ys, color=ROBOT, lw=0.9, alpha=0.35, zorder=2.5)

    for t, r in zip(L["tables"], results):
        draw_table(ax, t, ng=not r["reach"])

    sb = L["robot_standby"]
    x0, y0, x1, y1 = sb["rect"]
    ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="#fff4e6", ec=ROBOT, lw=1.4, zorder=5))
    n = sb["slots"]
    for i in range(n):
        ax.add_patch(Circle((x0 + (x1 - x0) * (i + 0.5) / n, (y0 + y1) / 2), 0.24, fc=ROBOT, ec="white", lw=0.8, zorder=6))

    mean = "-" if stats["mean_dist"] is None else f'{stats["mean_dist"]}m'
    mx = "-" if stats["max_dist"] is None else f'{stats["max_dist"]}m'
    ng = f'　届かない卓 {stats["tables"] - stats["reachable"]}（{stats["unreachable_seats"]}席）' if stats["reachable"] < stats["tables"] else ""
    line1 = f'{L["name"]}'
    line2 = f'{stats["seats"]}席・{W:g}m×{D:g}m　受け渡し口から卓まで 平均{mean}・最長{mx}{ng}'
    if small:
        ax.set_title(line1 + "\n" + line2, fontsize=8.5, loc="left", color=INK)
    else:
        ax.text(0, -1.25, line1 + "　" + line2, fontsize=10, color=INK, va="center")


# ---------------------------------------------------------------- 5パターン
def common_guest_keepouts(L, extra=()):
    """卓を置かない所（入口の通り道・レジ前・ドリンクバーの前後・受け渡し口と待機場所の前）"""
    ko = []
    e0, e1 = L["entrance"]["x0"], L["entrance"]["x1"]
    ko.append((e0 - 0.3, 0, e1 + 0.3, 2.8))
    for r in L["rooms"]:
        if r["label"] in ("レジ", "ドリンクバー"):
            x0, y0, x1, y1 = r["rect"]
            ko.append((x0 - 0.6, y0 - 1.3, x1 + 0.6, y1 + 1.3))
    for d in L["dish_up"]:
        x0, y0, x1, y1 = d["rect"]
        ko.append((x0 - 1.0, y0 - 1.8, x1 + 1.0, y1 + 1.8))
    x0, y0, x1, y1 = L["robot_standby"]["rect"]
    ko.append((x0 - 0.5, y0 - 1.2, x1 + 0.5, y1 + 0.5))
    return ko + list(extra)


def obstacles(L):
    return [r["rect"] for r in L["rooms"]] + [w["rect"] for w in L["walls"]] + [footprint(t) for t in L["tables"]]


def base_back_of_house():
    """ベース（記憶の店 v11）の裏側をそのまま使う"""
    base = json.load(open(HERE / "layout_v11.json", encoding="utf-8"))
    rooms = [r for r in base["rooms"] if r["label"] not in ("トイレ", "レジ", "ドリンクバー")]
    walls = [w for w in base["walls"] if w["label"] != "仕切り"]
    return base, rooms, walls


def v_open_hall():
    base, rooms, walls = base_back_of_house()
    L = dict(name="① 仕切りなし・大部屋型", outer=dict(w=24.0, d=17.0), entrance=dict(x0=9.6, x1=12.4),
             rooms=rooms + [dict(label="トイレ", rect=[7.4, 15.6, 9.5, 17.0], kind="guest"),
                            dict(label="レジ", rect=[10.0, 2.2, 12.2, 2.9], kind="guest"),
                            dict(label="ドリンクバー", rect=[13.4, 3.2, 18.6, 3.9], kind="drink")],
             walls=walls, dish_up=base["dish_up"], robot_standby=base["robot_standby"], start=[10.9, 5.5])
    L["tables"] = wall_booths("left", 0.2, 16.8, 0.0, zone="hall") + wall_booths("top", 1.5, 7.3, 17.0, zone="hall")
    L["tables"] += [t for t in base["tables"] if t["zone"] == "right"]
    L["tables"] += fill_tables([(1.3, 0.0, 9.5, 15.7)], obstacles(L) + common_guest_keepouts(L), gap=1.0, zone="hall")
    return L


def v_wide_back_kitchen():
    W, D = 26.0, 15.0
    L = dict(name="② 厨房が奥・横長型", outer=dict(w=W, d=D), entrance=dict(x0=11.5, x1=14.5),
             rooms=[dict(label="パントリー", rect=[8.0, 8.4, 20.0, 9.6], kind="back"),
                    dict(label="キッチン", rect=[8.0, 9.6, 20.0, 12.4], kind="back"),
                    dict(label="洗い場", rect=[8.0, 12.4, 14.0, 15.0], kind="back"),
                    dict(label="冷蔵・冷凍・保存", rect=[14.0, 12.4, 20.0, 15.0], kind="back"),
                    dict(label="更衣室・社員トイレ", rect=[20.0, 12.4, 26.0, 15.0], kind="back"),
                    dict(label="トイレ", rect=[0.0, 12.8, 2.6, 15.0], kind="guest"),
                    dict(label="レジ", rect=[9.0, 2.0, 11.0, 2.7], kind="guest"),
                    dict(label="ドリンクバー", rect=[16.0, 4.2, 20.0, 4.9], kind="drink")],
             walls=[], dish_up=[dict(label="受け渡し口", rect=[12.0, 8.4, 15.0, 8.8])],
             robot_standby=dict(label="ロボット待機・充電", rect=[15.4, 7.7, 17.6, 8.4], slots=3), start=[13.5, 7.9])
    L["tables"] = (wall_booths("left", 0.2, 12.6, 0.0, zone="left") + wall_booths("right", 0.2, 12.2, W, zone="right")
                   + wall_booths("top", 2.9, 7.9, D, zone="left"))
    L["tables"] += fill_tables([(1.3, 0.0, 24.7, 13.7)], obstacles(L) + common_guest_keepouts(L), gap=1.0, zone="hall")
    return L


def v_small():
    W, D = 18.0, 13.0
    L = dict(name="③ 小型店（面積はベースの約6割）", outer=dict(w=W, d=D), entrance=dict(x0=8.8, x1=11.0),
             rooms=[dict(label="パントリー", rect=[10.3, 5.0, 12.0, 10.8], kind="back"),
                    dict(label="キッチン", rect=[12.0, 5.0, 16.0, 10.8], kind="back"),
                    dict(label="冷蔵・冷凍・保存", rect=[16.0, 7.6, 18.0, 10.8], kind="back"),
                    dict(label="更衣室・社員トイレ", rect=[16.0, 5.0, 18.0, 7.6], kind="back"),
                    dict(label="洗い場", rect=[12.0, 11.6, 18.0, 13.0], kind="back"),
                    dict(label="トイレ", rect=[8.6, 11.6, 10.3, 13.0], kind="guest"),
                    dict(label="レジ", rect=[11.4, 1.6, 13.2, 2.3], kind="guest"),
                    dict(label="ドリンクバー", rect=[13.8, 3.0, 17.2, 3.6], kind="drink")],
             walls=[dict(label="パントリーの壁", rect=[10.0, 5.0, 10.3, 10.8])],
             dish_up=[dict(label="受け渡し口", rect=[10.3, 5.0, 12.0, 5.4])],
             robot_standby=dict(label="ロボット待機・充電", rect=[12.2, 4.3, 13.8, 4.9], slots=2), start=[11.1, 4.5])
    L["tables"] = wall_booths("left", 0.2, 12.8, 0.0, zone="hall") + wall_booths("top", 1.5, 8.5, D, zone="hall")
    L["tables"] += fill_tables([(1.3, 0.0, 10.0, 11.6)], obstacles(L) + common_guest_keepouts(L), gap=1.0, zone="hall")
    return L


def v_large():
    W, D = 30.0, 20.0
    L = dict(name="④ 大型店（厨房が真ん中の奥・受け渡し口2つ）", outer=dict(w=W, d=D), entrance=dict(x0=13.5, x1=16.5),
             rooms=[dict(label="パントリー", rect=[10.0, 10.5, 20.0, 11.6], kind="back"),
                    dict(label="キッチン", rect=[10.0, 11.6, 20.0, 16.0], kind="back"),
                    dict(label="洗い場", rect=[10.0, 16.0, 15.0, 20.0], kind="back"),
                    dict(label="冷蔵・冷凍・保存", rect=[15.0, 16.0, 20.0, 20.0], kind="back"),
                    dict(label="更衣室・社員トイレ", rect=[20.0, 17.0, 24.5, 20.0], kind="back"),
                    dict(label="トイレ", rect=[6.0, 17.6, 10.0, 20.0], kind="guest"),
                    dict(label="レジ", rect=[11.0, 2.0, 12.8, 2.7], kind="guest"),
                    dict(label="ドリンクバー", rect=[18.0, 4.2, 22.0, 4.9], kind="drink")],
             walls=[], dish_up=[dict(label="受け渡し口（左）", rect=[11.0, 10.5, 13.4, 10.9]),
                                dict(label="受け渡し口（右）", rect=[16.6, 10.5, 19.0, 10.9])],
             robot_standby=dict(label="ロボット待機・充電", rect=[13.8, 9.8, 16.2, 10.5], slots=3), start=[15.0, 9.4])
    L["tables"] = (wall_booths("left", 0.2, 19.6, 0.0, zone="left") + wall_booths("right", 0.2, 16.8, W, zone="right")
                   + wall_booths("top", 1.5, 5.9, D, zone="left") + wall_booths("top", 24.6, 28.7, D, zone="right"))
    L["tables"] += fill_tables([(1.3, 0.0, 28.7, 18.7)], obstacles(L) + common_guest_keepouts(L), gap=1.0, zone="hall")
    return L


def v_crammed():
    base = json.load(open(HERE / "layout_v11.json", encoding="utf-8"))
    L = {k: base[k] for k in ("outer", "entrance", "rooms", "walls", "dish_up", "robot_standby")}
    L["name"] = "⑤ 詰め込み型（ベースの客席を通路60cmで詰めた）"
    L["start"] = [10.9, 5.5]
    keep = [t for t in base["tables"] if t["type"] == "booth6L"]
    L["tables"] = keep
    ko = common_guest_keepouts(L)
    L["tables"] += fill_tables([(1.4, 9.0, 9.5, 17.0), (1.6, 0.0, 9.5, 8.6), (12.4, 0.0, 21.0, 6.0)],
                               obstacles(L) + ko, gap=0.6, zone="hall")
    return L


def load_base():
    L = json.load(open(HERE / "layout_v11.json", encoding="utf-8"))
    L["name"] = "ベース：記憶の店 v11"
    L["start"] = [10.9, 5.5]
    return L


def main():
    out_dir = HERE / "variants"
    out_dir.mkdir(exist_ok=True)
    layouts = [load_base(), v_open_hall(), v_wide_back_kitchen(), v_small(), v_large(), v_crammed()]
    names = ["v11_base", "p1_open_hall", "p2_wide_back_kitchen", "p3_small", "p4_large", "p5_crammed"]
    summary = []
    fig, axes = plt.subplots(3, 2, figsize=(15, 19), dpi=120)
    for L, nm, ax in zip(layouts, names, axes.flat):
        results, stats = analyze(L)
        json.dump(L, open(out_dir / f"{nm}.json", "w", encoding="utf-8"), ensure_ascii=False, indent=2)
        f1, a1 = plt.subplots(figsize=(14, 10.5), dpi=120)
        draw(a1, L, results, stats)
        f1.savefig(out_dir / f"{nm}.png", bbox_inches="tight", facecolor="white")
        plt.close(f1)
        draw(ax, L, results, stats, small=True)
        summary.append(dict(name=L["name"], file=nm, **stats))
    fig.text(0.02, 0.005, "オレンジの線＝待機場所の前から各卓までの一番短い道（ロボットの幅は仮に70cm）。赤い卓＝ロボットが届かない卓。寸法はすべて仮。",
             fontsize=10, color=INK)
    fig.tight_layout(rect=(0, 0.015, 1, 1))
    fig.savefig(out_dir / "overview.png", bbox_inches="tight", facecolor="white")
    json.dump(summary, open(out_dir / "summary.json", "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    for s in summary:
        print(s)


if __name__ == "__main__":
    main()
