"""最後の節の背景：⑤の店舗の図面（暗い地に細い線）と、待機場所から全卓へのロボットの道（最短の道を格子で探す）"""
import json, sys
from collections import deque
L = json.load(open(sys.argv[1]))['layout']; A = json.load(open(sys.argv[2]))
W, D = L['outer']['w'], L['outer']['d']; S = 0.1; R = 0.3
nx, ny = int(W / S), int(D / S)
block = [[False] * ny for _ in range(nx)]
def rect_block(x0, y0, x1, y1, pad):
    for i in range(max(0, int((x0 - pad) / S)), min(nx, int((x1 + pad) / S) + 1)):
        for j in range(max(0, int((y0 - pad) / S)), min(ny, int((y1 + pad) / S) + 1)):
            block[i][j] = True
for r in L['rooms']: rect_block(*r['rect'], R)
for w in L['walls']: rect_block(*w['rect'], R)
for t in L['tables']: rect_block(t['x'], t['y'], t['x'] + t['w'], t['y'] + t['h'], R - 0.05)
for i in range(nx):
    for j in range(ny):
        if i * S < R or j * S < R or i * S > W - R or j * S > D - R: block[i][j] = True
sx, sy = L['start']; s = (int(sx / S), int(sy / S))
prev = {s: None}; q = deque([s])
while q:
    c = q.popleft()
    for dx, dy in ((1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)):
        n = (c[0] + dx, c[1] + dy)
        if 0 <= n[0] < nx and 0 <= n[1] < ny and not block[n[0]][n[1]] and n not in prev:
            prev[n] = c; q.append(n)
def path(p):
    g = (round(p[0] / S), round(p[1] / S)); best = min(prev, key=lambda c: (c[0]-g[0])**2 + (c[1]-g[1])**2)
    out = []
    while best: out.append(best); best = prev[best]
    return out[::-1]
def simp(pts):
    o = [pts[0]]
    for a, b in zip(pts[1:], pts[2:]):
        d1 = (a[0]-o[-1][0], a[1]-o[-1][1]); d2 = (b[0]-a[0], b[1]-a[1])
        if d1[0]*d2[1] - d1[1]*d2[0] != 0: o.append(a)
    o.append(pts[-1]); return o
Y = lambda y: D - y
out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-1 -1 {W+2} {D+2}" preserveAspectRatio="xMidYMid slice">',
       f'<rect x="-50" y="-50" width="{W+100}" height="{D+100}" fill="#242424"/>',
       '<g fill="none" stroke="#fff" stroke-opacity=".22" stroke-width="0.04">']
for r in L['rooms']:
    x0, y0, x1, y1 = r['rect']; out.append(f'<rect x="{x0}" y="{Y(y1)}" width="{x1-x0:.3f}" height="{y1-y0:.3f}" fill="#fff" fill-opacity=".04"/>')
for w in L['walls']:
    x0, y0, x1, y1 = w['rect']; out.append(f'<rect x="{x0}" y="{Y(y1)}" width="{x1-x0:.3f}" height="{y1-y0:.3f}" fill="#fff" fill-opacity=".2"/>')
for t in L['tables']:
    out.append(f'<rect x="{t["x"]}" y="{Y(t["y"]+t["h"]):.3f}" width="{t["w"]}" height="{t["h"]}" rx="0.06"/>')
out.append('</g>')
e = L['entrance']
out.append(f'<path d="M0 0H{W}V{D}H{e["a1"]}M{e["a0"]} {D}H0Z" fill="none" stroke="#fff" stroke-opacity=".45" stroke-width="0.12"/>')
out.append('<g opacity=".32"><g fill="none" stroke="#f2600c" stroke-width="0.06" stroke-linecap="round" stroke-linejoin="round">')
for t in A['tables']:
    p = simp(path(t['stop']))
    out.append('<polyline points="' + ' '.join(f'{c[0]*S:.2f},{Y(c[1]*S):.2f}' for c in p) + '"/>')
out.append('</g><g fill="#f2600c">')
for t in A['tables']:
    out.append(f'<circle cx="{t["stop"][0]:.2f}" cy="{Y(t["stop"][1]):.2f}" r="0.11"/>')
x0, y0, x1, y1 = L['robot_standby']['rect']
out.append(f'</g></g><rect x="{x0}" y="{Y(y1)}" width="{x1-x0:.2f}" height="{y1-y0:.2f}" fill="#f2600c" fill-opacity=".45"/></svg>')
open(sys.argv[3], 'w').write('\n'.join(out))
print(len(A['tables']), 'routes')
