"""依頼310（agg291.py の写し。依頼291 の表も並べ、依頼310 の数（A 進めていない・B 待つ所）を足した）：条件ごとのまとめ（種5個の中央値と最小・最大）と試算との表・引っかかりの一覧・拭き残りの場所・壁の際の比べ。
使い方: python3 agg310.py  → ../tables/ に CSV と md"""
import os, sys, csv, json, statistics, collections
import numpy as np
from scipy import ndimage
HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE); import grid291 as grid290
OUT = os.path.join(ROOT, 'tables'); os.makedirs(OUT, exist_ok=True)
P = json.load(open(os.path.expanduser('~/Robotics_UX/ServiceSim/Assets/ServiceSim/Cleaning/Data/cleaning-unity-params.json')))
L = json.load(open(os.path.expanduser('~/Robotics_UX/ServiceSim/Assets/ServiceSim/Cleaning/Data/mall_m1.json')))
SITE = {r['robots']: r for r in P['site_reference']['rows']}
NIGHT = 28800
idx = [r for r in csv.DictReader(open(os.path.join(ROOT, 'index310.csv'))) if r['label'] in ('main310', 'edge310')]
runs = {}
for r in idx:
    d = os.path.join(ROOT, r['folder'])
    s = json.load(open(os.path.join(d, 'summary.json')))
    runs[r['run']] = (r, s, d)

def cond_key(r): return (r['label'], int(r['robots']), r['split'])
conds = collections.OrderedDict()
for name in sorted(runs, key=lambda n: (runs[n][0]['label'], int(runs[n][0]['robots']), runs[n][0]['split'] != 'split', int(runs[n][0]['seed']))):
    conds.setdefault(cond_key(runs[name][0]), []).append(name)

def mins(t): return None if t is None or t < 0 else t / 60.0
def stat(v):
    v = [y for x in v for y in (x if isinstance(x, list) else [x])]
    v = [x for x in v if x is not None]
    if not v: return ('—', '—', '—')
    return (round(statistics.median(v), 3), round(min(v), 3), round(max(v), 3))
def fmt(t): return f'{t[0]}（{t[1]}〜{t[2]}）' if t[0] != '—' else '—'

METRICS = [
    ('robot_done_min', '1 ロボットの床を拭き終えた（22:00 からの分。終わらなければ —）', lambda s: mins(s['robot_floor_done_t_s'])),
    ('robot_on_time', '1 ロボットの床が 6:00 に間に合った回（5回のうち）', None),
    ('all_done_min', '1 全部（ロボットの床・人の床）拭き終えた（22:00 からの分。終わらなければ —）', lambda s: mins(s['all_done_t_s'])),
    ('people_done_min', '1 人の床を拭き終えた（分）', lambda s: mins(s['people_floor_done_t_s'])),
    ('robot_share_all', '2 ロボットの床の拭けた割合（ロボット＋清掃員の手伝い。6:00 または終わった時）', lambda s: s['robot_floor_cleaned_share_all']),
    ('robot_share', '2 うちロボットが拭いた割合', lambda s: s['robot_cleaned_share']),
    ('calls', '3 人が呼ばれた回数（水＋引っかかり）', lambda s: s['calls']),
    ('tank_calls', '3 うち水', lambda s: s['tank_calls']),
    ('stuck_calls', '3 うち引っかかり', lambda s: s['stuck_calls']),
    ('call_min', '3 呼び出しに使った分（清掃員。歩く＋作業）', lambda s: s['call_min']),
    ('robot_wait_min', '3 ロボットが人を待って止まった分（全台の合計）', lambda s: s['robot_wait_min']),
    ('snags', '4 引っかかった回数（人が行かない分も入れる）', lambda s: s['snags']),
    ('faceoffs', '5 ロボットどうしが向かい合って止まった回数', lambda s: s['faceoffs']),
    ('stalls_30s', '5 30秒以上の立ち往生の回数', lambda s: s['stalls_30s']),
    ('stall_calls', '5 うち清掃員が動かしに行った回数', lambda s: s['stall_rescue_calls']),
    ('walk_m', '6 清掃員が歩いた距離（3人の合計・m）', lambda s: s['staff_walk_m']),
    ('walk_own_m', '6 うち自分の担当', lambda s: s['staff_walk_own_m']),
    ('walk_call_m', '6 うち呼び出しに応えた分', lambda s: s['staff_walk_call_m']),
    ('walk_other_m', '6 うち控室への行き帰り', lambda s: s['staff_walk_other_m']),
    ('walk_help_m', '6 うち広い床の手伝い', lambda s: s['staff_walk_help_m']),
    ('walk_wait_m', '6 うちその場で待つ間によけて動いた分（依頼273。290 はロボットをよけた分も入る）', lambda s: s.get('staff_walk_wait_m')),
    ('wait_min', '9 清掃員がその場で待った時間（3人の合計・分・依頼273）', lambda s: s.get('staff_wait_min')),
    ('waits', '9 その場で待ち始めた回数（3人の合計・依頼273）', lambda s: s.get('staff_waits')),
    ('wait_avoids', '9 その場で待つ間にロボットをよけた回数（3人の合計・依頼290）', lambda s: s.get('staff_wait_avoids')),
    ('rate_lane', '8 Unity の拭く速さ（㎡/分・全台。ロボットが拭いたロボットの床 ÷ 線の仕事の時間＝線へ移る＋拭く）', lambda s: s['robot_rate_lane_m2_per_min']),
    ('rate_clean', '8 （参考）拭いて走っている間だけの速さ（㎡/分）', lambda s: s['robot_rate_clean_m2_per_min']),
    ('help_min', '9 清掃員が広い床を手伝った時間（3人の合計・分。歩く＋拭く）', lambda s: s['staff_help_min']),
    ('help_clean_min', '9 うち拭いていた分', lambda s: s['staff_help_clean_min']),
    ('help_m2', '9 手伝って拭いた広さ（ロボットの床・㎡）', lambda s: s['staff_help_m2']),
    ('charge_trips', '10 充電で控室まで戻った回数（全台）', lambda s: s['charge_trips']),
    ('charge_stop_min', '10 戻る・充電・線へ戻るで止まった分（全台）', lambda s: s['charge_stop_min']),
    ('charge_to_min', '10 うち控室へ戻る', lambda s: s['charge_to_dock_min']),
    ('charge_back_min', '10 うち線へ戻る', lambda s: s['charge_back_min']),
    ('shared_avoid', '11 shared でほかの台の線に入るのを避けた回数', lambda s: s['shared_avoid']),
    ('line_wait_min', '11 取れる線が無く待った分（全台）', lambda s: s['line_wait_min']),
    ('staff_work_h', '（参考）清掃員の手を動かした時間（拭く＋手伝い＋呼び出し・時間）', lambda s: s['staff_work_h']),
    ('robot_share_floor', '（参考）施設の床のうちロボットが拭いた割合', lambda s: s['robot_share_area_of_floor']),
    ('kiri_count', '12 切り返しをした回数（1晩・全台。依頼291）', lambda s: s.get('kiri_count')),
    ('kiri_min', '12 切り返しに使った時間（1晩・全台・分）', lambda s: s.get('kiri_min')),
    ('kiri_count_per_robot', '12 切り返しをした回数（台ごと・1晩）', lambda s: [b.get('kiri_count') for b in s['per_robot']]),
    ('kiri_min_per_robot', '12 切り返しに使った時間（台ごと・1晩・分）', lambda s: [b.get('kiri_min') for b in s['per_robot']]),
    ('kiri_arcs', '12 切り返しの動き（弧）の数（全台）', lambda s: s.get('kiri_arcs')),
    ('goal_shifts', '12 切り返しでも入れず、線へ移る行き先を壁から離した所へずらした回数（全台）', lambda s: s.get('goal_shifts')),
    ('no_progress_trips', '13 その場で向きを変えるなどで 10 秒に 0.5 m 進めず止まりに数え始めた回数（全台・依頼310 A）', lambda s: s.get('no_progress_trips')),
    ('line_wait_moves', '13 線が空くのを待つ所へ動いた回数（全台・依頼310 B）', lambda s: s.get('line_wait_moves')),
    ('line_wait_pushes', '13 人が線が空くのを待つ台を待つ所へ動かした回数（依頼310 B）', lambda s: s.get('line_wait_pushes')),
    ('rect_turns', '（参考）その場で回った回数（45°ごと・全台）', lambda s: s.get('rect_turns')),
    ('rect_reverse_m', '（参考）下がった距離（m・全台）', lambda s: s.get('rect_reverse_m')),
    ('ov', '（確かめ）長方形と壁・物・ほかの台の重なり（毎コマの数）', lambda s: s['rect_overlap_static_frames'] + s['rect_overlap_robot_frames']),
    ('jumps', '（確かめ）瞬間移動', lambda s: s['robot_jumps'] + s['person_jumps']),
]
rows = []
for k, names in conds.items():
    ss = [runs[n][1] for n in names]
    row = {'label': k[0], 'robots': k[1], 'split': k[2], 'n': len(names)}
    for key, _, f in METRICS:
        if key == 'robot_on_time':
            row[key] = sum(1 for s in ss if 0 <= s['robot_floor_done_t_s'] <= NIGHT)
        else:
            row[key] = stat([f(s) for s in ss])
    rows.append(row)
with open(os.path.join(OUT, 'conditions310.csv'), 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['label', 'robots', 'split', 'n'] + [m[0] + s for m in METRICS for s in ('_med', '_min', '_max')])
    for r in rows:
        w.writerow([r['label'], r['robots'], r['split'], r['n']] + [x for m in METRICS for x in (r[m[0]] if isinstance(r[m[0]], tuple) else (r[m[0]], '', ''))])

# ---- 8 Unity の拭く速さ：台ごと・回ごと ----
rr = [['run', 'robots', 'split', 'edge', 'seed', 'robot', 'area_m2', 'lane_min', 'rate_lane_m2_per_min', 'clean_min', 'rate_clean_m2_per_min']]
for n, (r, s, d) in sorted(runs.items()):
    for b in s['per_robot']:
        rr.append([n, r['robots'], r['split'], r['edge'], r['seed'], b['id'], b['area_m2'], b['lane_min'], b['rate_lane_m2_per_min'], b['clean_min'], b['rate_clean_m2_per_min']])
with open(os.path.join(OUT, 'rate310_per_robot.csv'), 'w', newline='', encoding='utf-8') as f:
    csv.writer(f).writerows(rr)

# ---- 試算と並べた表（main だけ）----
md = ['## 条件ごとのまとめ（種0〜4 の中央値（最小〜最大））\n']
mains = [r for r in rows if r['label'] == 'main310']
hdr = '| 項目 | ' + ' | '.join(f"{r['robots']}台 {r['split'] if r['robots'] > 1 else ''}".strip() for r in mains) + ' |'
md.append(hdr); md.append('|' + '---|' * (len(mains) + 1))
for key, name, _ in METRICS:
    md.append(f'| {name} | ' + ' | '.join(fmt(r[key]) if isinstance(r[key], tuple) else str(r[key]) for r in mains) + ' |')
md.append('\n## 試算（site_reference・同じ台数・30回の平均）\n')
md.append('| 項目 | 1台 | 2台 | 3台 |'); md.append('|---|---|---|---|')
for k, name in [('finish', '全部終わった（分）'), ('on_time', '6:00 に間に合った割合'), ('staff_hours', '清掃員の時間'), ('calls', '呼ばれた回数'),
                ('tank_calls', 'うち水'), ('stuck_calls', 'うち引っかかり'), ('call_min', '呼び出しに使った分'), ('robot_wait', 'ロボットが待った分'),
                ('robot_share_area', '施設の床のうちロボットが拭いた割合')]:
    md.append(f'| {name} | ' + ' | '.join(str(SITE[n][k]) for n in (1, 2, 3)) + ' |')
for req, folder in (('291', '20261125_mall291'), ('290', '20261124_mall290'), ('273', '20261123_mall273'), ('269', '20261123_mall269')):
    old = {}
    fn = os.path.join(os.path.dirname(ROOT), folder, 'tables', f'conditions{req}.csv')
    if not os.path.exists(fn): continue
    for r in csv.DictReader(open(fn, encoding='utf-8')):
        old[(r['label'].replace(req, '310'), int(r['robots']), r['split'])] = r
    md.append(f'\n## 依頼{req} の結果（同じ条件・種0〜4 の中央値（最小〜最大））\n')
    md.append(hdr); md.append('|' + '---|' * (len(mains) + 1))
    for key, name, _ in METRICS:
        vals = []
        for r in mains:
            o = old.get(('main310', r['robots'], r['split']))
            if o is None or (key + '_med') not in o: vals.append('—'); continue
            if key == 'robot_on_time': vals.append(o[key + '_med']); continue
            vals.append(f"{o[key + '_med']}（{o[key + '_min']}〜{o[key + '_max']}）" if o[key + '_med'] != '—' else '—')
        md.append(f'| {name} | ' + ' | '.join(vals) + ' |')
open(os.path.join(OUT, 'conditions310.md'), 'w', encoding='utf-8').write('\n'.join(md) + '\n')

# ---- 引っかかりの一覧（全部の回）----
allsn = []
for n, (r, s, d) in runs.items():
    for x in csv.DictReader(open(os.path.join(d, 'snags.csv'), encoding='utf-8')):
        x = dict(x); x['obj_label'] = x['label']; x['run'] = n; x['label'] = r['label']; x['robots'] = r['robots']; x['split'] = r['split']; x['seed'] = r['seed']; allsn.append(x)
with open(os.path.join(OUT, 'snags310_all.csv'), 'w', newline='', encoding='utf-8') as f:
    keys = ['run', 'label', 'robots', 'split', 'seed', 'snag', 't_s', 'robot', 'x', 'z', 'obj_id', 'kind', 'label_obj', 'snag_kind', 'staff_called', 'staff', 'resolve_s', 'call']
    w = csv.writer(f); w.writerow(keys)
    for x in allsn:
        w.writerow([x['run'], x['label'], x['robots'], x['split'], x['seed'], x['snag'], x['t_s'], x['robot'], x['x'], x['z'], x['obj_id'], x['kind'], x['obj_label'], x['snag_kind'], x['staff_called'], x['staff'], x['resolve_s'], x['call']])
mainsn = [x for x in allsn if x['label'] == 'main310']
objs = {i: o for i, o in enumerate(L['objects'])}
def objname(oid):
    oid = int(oid)
    if oid >= 1000:
        m = L['mats'][oid - 1000]; return f'マット{oid - 1000}（{(m[1] + m[3]) / 2:.0f},{(m[2] + m[4]) / 2:.0f}）'
    o = objs[oid]; r = o['rect']; return f"{o['label']}#{oid}（{(r[0] + r[2]) / 2:.1f},{(r[1] + r[3]) / 2:.1f}）"
by_obj = collections.Counter(x['obj_id'] for x in mainsn)
by_kind = collections.Counter(x['snag_kind'] for x in mainsn)
zone_names = [f[0] for f in L['floor']]
def zone_of(x, z):
    for f in L['floor']:
        if f[1] <= x <= f[3] and f[2] <= z <= f[4]: return f[0]
    return '床の外'
by_zone = collections.Counter(zone_of(float(x['x']), float(x['z'])) for x in mainsn)
lines = ['## 引っかかり（本番 25 回の合計）\n', f'全部 {len(mainsn)} 回 / 人が行った {sum(1 for x in mainsn if x["staff_called"] == "1")} 回\n',
         '### 物ごと（上から10）', '| 物 | 回数 |', '|---|---|']
lines += [f'| {objname(k)} | {v} |' for k, v in by_obj.most_common(10)]
lines += ['', '### 種類ごと', '| 種類 | 回数 | 物の数 |', '|---|---|---|']
cnt_kind = collections.Counter(o['snag'] for o in L['objects'] if o['snag']); cnt_kind['マットの端'] = len(L['mats'])
lines += [f'| {k} | {v} | {cnt_kind.get(k, 0)} |' for k, v in by_kind.most_common()]
lines += ['', '### 場所（床の名前）ごと', '| 場所 | 回数 |', '|---|---|'] + [f'| {k} | {v} |' for k, v in by_zone.most_common()]
res = [float(x['resolve_s']) for x in mainsn if float(x['resolve_s']) >= 0]
lines += ['', f'解けるまでの秒：中央値 {statistics.median(res):.0f}・最大 {max(res):.0f}（人が行った回 {statistics.median([float(x["resolve_s"]) for x in mainsn if x["staff_called"] == "1" and float(x["resolve_s"]) >= 0] or [0]):.0f}）' if res else '']
open(os.path.join(OUT, 'snags310.md'), 'w', encoding='utf-8').write('\n'.join(lines) + '\n')

# ---- 拭き残り（6:00 または終わった時。ロボットの床のうち、ロボットが拭いていないマス）----
zone_mask = None
left_rows = []
leftsum = {}
for n, (r, s, d) in runs.items():
    g = grid290.read(os.path.join(d, 'grid.bin.gz'))
    rb = g['robot'].astype(bool); un = rb & (g['clean_t'] < 0)   # 依頼290：清掃員の手伝いも拭いたに数える
    if zone_mask is None:
        H, W = rb.shape; zone_mask = np.full((H, W), -1, np.int16)
        for zi in range(len(L['floor']) - 1, -1, -1):
            f = L['floor'][zi]; zone_mask[int(round(f[2] * 10)):int(round(f[4] * 10)), int(round(f[1] * 10)):int(round(f[3] * 10))] = zi
    k = cond_key(r)
    leftsum.setdefault(k, np.zeros(rb.shape, np.int16)); leftsum[k] += un
    for zi, name in enumerate(zone_names):
        c = int((un & (zone_mask == zi)).sum())
        left_rows.append([n, r['label'], r['robots'], r['split'], r['seed'], name, c * 0.01, int((rb & (zone_mask == zi)).sum()) * 0.01])
with open(os.path.join(OUT, 'leftover310_by_zone.csv'), 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f); w.writerow(['run', 'label', 'robots', 'split', 'seed', 'zone', 'left_m2', 'robot_floor_m2']); w.writerows(left_rows)
np.savez_compressed(os.path.join(OUT, 'leftover310_sum.npz'), **{f'{k[0]}_r{k[1]}_{k[2]}': v for k, v in leftsum.items()})
lz = ['## 拭き残り（ロボットの床・場所ごと・種5個の中央値 ㎡）\n', '| 場所 | ロボットの床 ㎡ | ' + ' | '.join(f'{k[1]}台 {k[2]}' + (' 壁の際' if k[0] == 'edge310' else '') for k in conds) + ' |',
      '|---|---|' + '---|' * len(conds)]
for name in zone_names:
    vals = []
    for k in conds:
        v = [row[6] for row in left_rows if (row[1], int(row[2]), row[3]) == k and row[5] == name]
        vals.append(f'{statistics.median(v):.1f}')
    tot = [row[7] for row in left_rows if row[5] == name][0]
    lz.append(f'| {name} | {tot:.0f} | ' + ' | '.join(vals) + ' |')
open(os.path.join(OUT, 'leftover310.md'), 'w', encoding='utf-8').write('\n'.join(lz) + '\n')

# ---- 壁の際の比べ（edge310 と main290 の 2台 split）----
cols = [o for o in L['objects'] if o['kind'] == 'column']
def edge_class(g):
    """壁の際の帯（本番の edge_wall_m の帯）のマスを、柱の根元・物のそば・角・入口の脇・まっすぐな壁に分ける"""
    wb = g['wall_band'].astype(bool); H, W = wb.shape
    yy, xx = np.nonzero(wb); x = (xx + 0.5) / 10; z = (yy + 0.5) / 10
    cls = np.full(len(x), 'まっすぐな壁', object)
    floor = np.zeros((H, W), bool)
    for f in L['floor']: floor[int(round(f[2] * 10)):int(round(f[4] * 10)), int(round(f[1] * 10)):int(round(f[3] * 10))] = True
    # 角：床の外のマスが2方向（x と z）の両方に 1.0 m 以内にある
    nx = ndimage.distance_transform_edt(floor, sampling=1)  # unused but keeps shape
    def near_out(dx, dz):
        ok = np.zeros(len(x), bool)
        for s in range(1, 11):
            ix = np.clip(xx + dx * s, 0, W - 1); iz = np.clip(yy + dz * s, 0, H - 1)
            ok |= ~floor[iz, ix]
        return ok
    ox = near_out(1, 0) | near_out(-1, 0); oz = near_out(0, 1) | near_out(0, -1)
    cls[ox & oz] = 'シャッター・壁の角'
    for f in L['floor']:
        if '入口' in f[0]:
            m = (x >= f[1]) & (x <= f[3]) & (z >= f[2]) & (z <= f[4]); cls[m & (cls == 'まっすぐな壁')] = '入口の脇'
    for o in L['objects']:
        r = o['rect']; dxo = np.maximum(np.maximum(r[0] - x, x - r[2]), 0); dzo = np.maximum(np.maximum(r[1] - z, z - r[3]), 0)
        m = np.hypot(dxo, dzo) <= 1.0
        cls[m] = '柱の根元' if o['kind'] == 'column' else '物のそば'
    return yy, xx, cls
er = []
edge_sum = None
for k in [('main310', 2, 'split'), ('edge310', 2, 'split')]:
    for n in conds.get(k, []):
        r, s, d = runs[n]
        g = grid290.read(os.path.join(d, 'grid.bin.gz'))
        yy, xx, cls = edge_class(g)
        robot_clean = (g['clean_t'][yy, xx] >= 0) & (g['clean_by'][yy, xx] < 10)
        if k[0] == 'edge310':
            if edge_sum is None: edge_sum = np.zeros(g['robot'].shape, np.int16)
            edge_sum[yy[~robot_clean], xx[~robot_clean]] += 1
        for c in ['柱の根元', '物のそば', 'シャッター・壁の角', '入口の脇', 'まっすぐな壁']:
            m = cls == c
            er.append([n, k[0], r['seed'], c, int(m.sum()), int((m & robot_clean).sum()), int((m & ~robot_clean).sum())])
        er.append([n, k[0], r['seed'], '全部', len(cls), int(robot_clean.sum()), int((~robot_clean).sum())])
        anyc = g['clean_t'][yy, xx] >= 0
        er.append([n, k[0], r['seed'], '全部（清掃員の手伝いも入れて拭けた）', len(cls), int(anyc.sum()), int((~anyc).sum())])
with open(os.path.join(OUT, 'edge310.csv'), 'w', newline='', encoding='utf-8') as f:
    w = csv.writer(f); w.writerow(['run', 'label', 'seed', 'where', 'band_cells', 'robot_cleaned_cells', 'left_cells']); w.writerows(er)
if edge_sum is not None: np.savez_compressed(os.path.join(OUT, 'edge310_left_sum.npz'), left=edge_sum)
el = ['## 壁の際の比べ（壁の際 0.8 m の帯のうちロボットが拭けた割合・種5個の中央値（最小〜最大））\n', '| 場所 | 帯の広さ ㎡ | 本番 2台 split | 壁の際も拭く 2台 split | 壁の際も拭く で残った ㎡（中央値） |', '|---|---|---|---|---|']
for c in ['全部', '全部（清掃員の手伝いも入れて拭けた）', '柱の根元', '物のそば', 'シャッター・壁の角', '入口の脇', 'まっすぐな壁']:
    def sh(lab):
        v = [e[5] / e[4] for e in er if e[1] == lab and e[3] == c and e[4] > 0]
        return stat(v)
    band = [e[4] for e in er if e[3] == c][0] * 0.01 if any(e[3] == c for e in er) else 0
    left = [e[6] * 0.01 for e in er if e[1] == 'edge310' and e[3] == c]
    el.append(f'| {c} | {band:.0f} | {fmt(sh("main310"))} | {fmt(sh("edge310"))} | {statistics.median(left) if left else 0:.1f} |')
open(os.path.join(OUT, 'edge310.md'), 'w', encoding='utf-8').write('\n'.join(el) + '\n')
print('\n'.join(md)); print('\n'.join(lines)); print('\n'.join(lz)); print('\n'.join(el))
