"""依頼291：壁の際の比べ（2台 split・壁の際も拭く・種0〜4）を依頼269・273・290 と並べる → ../tables/edge291_compare.md
① 壁からの距離ごとにロボットが拭けた割合（edge290c.py と同じ数え方）② 場所ごと（各依頼の tables/edge*.csv。agg291.py の後に回す）
③ 壁ぞいの線（線と平行な壁）の側と線の端（線と直角な壁）の側に分けた 0〜0.3 m（edgedir291.py と同じ数え方）"""
import os, sys, csv, json, statistics
import numpy as np
from scipy import ndimage
HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.dirname(HERE); UP = os.path.dirname(ROOT)
sys.path.insert(0, HERE); import grid291
L = json.load(open(os.path.expanduser('~/Robotics_UX/ServiceSim/Assets/ServiceSim/Cleaning/Data/mall_m1.json')))
BINS = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
REQ = [('269', os.path.join(UP, '20261123_mall269')), ('273', os.path.join(UP, '20261123_mall273')), ('290', os.path.join(UP, '20261124_mall290')), ('291', ROOT)]
floor = None; zone = None; dw = None; par = None
def prep(shape):
    global floor, zone, dw, par
    H, W = shape
    floor = np.zeros((H, W), bool); zone = -np.ones((H, W), int)
    for zi in range(len(L['floor']) - 1, -1, -1):
        f = L['floor'][zi]; sl = (slice(int(round(f[2] * 10)), int(round(f[4] * 10))), slice(int(round(f[1] * 10)), int(round(f[3] * 10))))
        floor[sl] = True; zone[sl] = zi
    dist, ind = ndimage.distance_transform_edt(floor, return_indices=True)
    dw = dist * 0.1 - 0.05
    zz, xx = np.mgrid[0:H, 0:W]; vz = zz - ind[0]; vx = xx - ind[1]
    alongx = np.array([(f[3] - f[1]) >= (f[4] - f[2]) for f in L['floor']])
    ax = np.where(zone >= 0, alongx[np.maximum(zone, 0)], False)
    par = np.where(ax, np.abs(vz) > np.abs(vx), np.abs(vx) > np.abs(vz))
res = {}
for req, root in REQ:
    rows = []
    for s in range(5):
        g = grid291.read(os.path.join(root, 'runs', f'edge{req}_r2_split_edge_s{s}', 'grid.bin.gz'))
        if floor is None: prep(g['robot'].shape)
        wb = g['wall_band'].astype(bool); cl = (g['clean_t'] >= 0) & (g['clean_by'] < 10)
        r = []
        for a, b in zip(BINS[:-1], BINS[1:]):
            m = wb & (dw >= a - 1e-6) & (dw < b - 1e-6); r.append((m & cl).sum() / max(1, m.sum()))
        m3 = wb & (dw < 0.3 - 1e-6)
        r.append((m3 & cl).sum() / m3.sum()); r.append((m3 & ~cl).sum() * 0.01)
        for sel in (m3 & par, m3 & ~par):
            r.append((sel & cl).sum() / max(1, sel.sum())); r.append((sel & ~cl).sum() * 0.01)
        r.append((wb & cl).sum() / wb.sum()); r.append((wb & ~cl).sum() * 0.01)
        rows.append(r)
    res[req] = np.array(rows)
def cell(a, pct=True):
    med, lo, hi = np.median(a), a.min(), a.max()
    return (f'{100*med:.1f}%（{100*lo:.1f}〜{100*hi:.1f}）' if pct else f'{med:.1f}（{lo:.1f}〜{hi:.1f}）')
md = ['## 壁の際の比べ（2台 split・壁の際も拭く edge_wall_m 0.0・種0〜4 の中央値（最小〜最大））\n',
      '### 壁（床の外）からの距離ごとの、ロボットが拭けた割合', '| 壁からの距離 | 依頼269 | 依頼273 | 依頼290 | 依頼291 |', '|---|---|---|---|---|']
for i, (a, b) in enumerate(zip(BINS[:-1], BINS[1:])):
    md.append(f'| {a:.1f}〜{b:.1f} m | ' + ' | '.join(cell(res[q][:, i]) for q, _ in REQ) + ' |')
n = len(BINS) - 1
md.append(f'| 0.0〜0.3 m | ' + ' | '.join(cell(res[q][:, n]) for q, _ in REQ) + ' |')
md.append(f'| 0.0〜0.3 m の残り ㎡ | ' + ' | '.join(cell(res[q][:, n + 1], False) for q, _ in REQ) + ' |')
md.append(f'| 0.0〜0.3 m のうち壁ぞいの線の側（線と平行な壁） | ' + ' | '.join(cell(res[q][:, n + 2]) for q, _ in REQ) + ' |')
md.append(f'| 　同 残り ㎡ | ' + ' | '.join(cell(res[q][:, n + 3], False) for q, _ in REQ) + ' |')
md.append(f'| 0.0〜0.3 m のうち線の端の側（線と直角な壁） | ' + ' | '.join(cell(res[q][:, n + 4]) for q, _ in REQ) + ' |')
md.append(f'| 　同 残り ㎡ | ' + ' | '.join(cell(res[q][:, n + 5], False) for q, _ in REQ) + ' |')
md.append(f'| 帯全体（0.0〜0.8 m） | ' + ' | '.join(cell(res[q][:, n + 6]) for q, _ in REQ) + ' |')
md.append(f'| 帯全体の残り ㎡ | ' + ' | '.join(cell(res[q][:, n + 7], False) for q, _ in REQ) + ' |')
# 場所ごと
md += ['', '### 場所ごと（壁の際 0.8 m の帯。拭けた割合・残り ㎡）', '| 場所 | 帯の広さ ㎡ | 依頼269 | 依頼273 | 依頼290 | 依頼291 |', '|---|---|---|---|---|---|']
E = {}
for req, root in REQ:
    fn = os.path.join(root, 'tables', f'edge{req}.csv')
    if os.path.exists(fn): E[req] = [r for r in csv.DictReader(open(fn, encoding='utf-8')) if r['label'] == f'edge{req}']
for c in ['全部', '全部（清掃員の手伝いも入れて拭けた）', '柱の根元', '物のそば', 'シャッター・壁の角', '入口の脇', 'まっすぐな壁']:
    vals = []; band = None
    for req, _ in REQ:
        rr = [r for r in E.get(req, []) if r['where'] == c]
        if not rr: vals.append('—'); continue
        band = int(rr[0]['band_cells']) * 0.01
        sh = statistics.median(int(r['robot_cleaned_cells']) / int(r['band_cells']) for r in rr)
        left = statistics.median(int(r['left_cells']) * 0.01 for r in rr)
        vals.append(f'{100*sh:.1f}%・{left:.1f}')
    md.append(f'| {c} | {band:.0f} | ' + ' | '.join(vals) + ' |')
out = '\n'.join(md) + '\n'
open(os.path.join(ROOT, 'tables', 'edge291_compare.md'), 'w', encoding='utf-8').write(out); print(out)
