"""依頼271：make270.py を写して変えた。
(1) closeup271_<名前>.mp4：frames/<場面>/f_*.png（台本の video_from から終わりまで）に台本の秒の音（mix271_<場面>.wav）を重ねる。
(2) closeup271_<名前>_top.mp4：frames/<場面>_top に 236 の描き方で床の目印・通った跡・印・左上の字を重ねる。
    目印：角の壁の線（内側の角の壁の面 x 0.90・z −0.90。実線）・ハコブくんの線（ふだんの線と曲がる線。点線）。床の目印は、ものごとに穴を埋めた外形の中には描かない。
    もの：ハコブくん（赤）と、車いす・茂さん・大城さん（緑。手を握りにのせたままなので 1 つのもの。236 と同じ考え）
    印：「見つけた」「止まった」（ハコブくんの根。字に動画の秒）。左上の字：動画の秒・ハコブくんの速さ・ハコブくんと車いす（人を含む）のすき間
    重ねる順：コマ → 床の目印（外形の所は消す）→ 通った跡 → 印 → 左上の字
使い方: python3 make271.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ> <動画の名前>"""
import csv, json, math, os, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD, NAME = sys.argv[1:7]
os.makedirs(os.path.join(VD, "stills"), exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c271"]
FPS, W, H, S = 30, 1920, 1080, 2
f0 = int(round(C["video_from"] * FPS)); f1 = int(round(C["video_to"] * FPS))
seq = list(range(f0, f1 + 1))
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
vmap = {f: (f - f0) / FPS for f in seq}

# ---------------------------------------------------------------- (1) 本番の動画（TOP_ONLY=1 なら作らない）
TOP_ONLY = os.environ.get("TOP_ONLY") == "1"
tmp = tempfile.mkdtemp(prefix="m271_", dir="/tmp")
if not TOP_ONLY:
    for k, f in enumerate(seq):
        src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png"))
    wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
    a0 = int(round(f0 / FPS * SR)); a1 = int(round((f1 + 1) / FPS * SR))
    aud = x[a0:a1]; aud = np.pad(aud, (0, max(0, a1 - a0 - len(aud))))
    aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(aud.astype(np.int16).tobytes()); w2.close()
    vid = os.path.join(VD, f"{NAME}.mp4")
    subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                    "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                    "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
    json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "video_from": C["video_from"]},
              open(os.path.join(D, f"vmap271_{SHOT}.json"), "w"), ensure_ascii=False)
    print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒")

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top271_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 48, 32, 34
COL = {"wall": (142, 36, 170), "lane": (46, 173, 107), "chair": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"wall": 6, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames271.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top271.csv")))}
EV = C["events"]; K = C["corner"]
MARKS = [("robot", EV["det"], "見つけた"), ("robot", EV["stopR"], "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed_poly(d, pts, col, w):
    s_acc = 0.0; on = True; lim = DASH * S
    for (p0, p1) in zip(pts[:-1], pts[1:]):
        (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0)
        if L < 1e-9: continue
        ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
        while s < L:
            step = min(L - s, lim - s_acc)
            if on: d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * (s + step), y0 + uy * (s + step))], fill=col, width=w * S)
            s += step; s_acc += step
            if s_acc >= lim - 1e-9: on = not on; s_acc = 0.0; lim = (DASH if on else GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
x_lo, z_lo = from_px(0, H); x_hi, z_hi = from_px(W, 0)
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
wl = K["wall"]
# 角の壁の線（内側の角の壁の面）：A の側 x 0.90（z −0.90 から手前へ）と B の側 z −0.90（x 0.90 から奥へ）
d.line([sc(to_px(wl, z_lo - 1)), sc(to_px(wl, -wl)), sc(to_px(x_hi + 1, -wl))], fill=COL["wall"] + (255,), width=LW["wall"] * S, joint="curve")
pc = to_px(wl, -wl)
text_box(d, sc((pc[0] + 16, pc[1] + 16)), "角の壁の線", FL, COL["wall"], "lt", edge=COL["wall"])
# ハコブくんの線：A の x −0.33 → 半径 R の円弧 → B の z +0.33
R = K["r_turn"]; zs = K["lane_robot_b"] - R; cxa = K["lane_robot"] + R
pts = [to_px(K["lane_robot"], z_lo - 1), to_px(K["lane_robot"], zs)]
for i in range(1, 41):
    th = math.pi / 2 * i / 40; pts.append(to_px(cxa - R * math.cos(th), zs + R * math.sin(th)))
pts.append(to_px(x_hi + 1, K["lane_robot_b"]))
dashed_poly(d, pts, COL["lane"] + (255,), LW["dash"])
lp = to_px(K["lane_robot"], z_lo)
text_box(d, sc((lp[0] - 14, H - 14)), "ハコブくんの線", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A")
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = float(r["robot_px"]), float(r["robot_py"])
        lx, ly = to_px(2.0, 0.0)[0] + 0.0, py + (60 if i == 0 else -60)
        lx = to_px(1.6, 0)[0]
        ly = py + 70 * (1 if i == 0 else -1)
        d.line([sc((px, py)), sc((lx, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        Rr = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - Rr - e, py * S - Rr - e, px * S + Rr + e, py * S + Rr + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - Rr, py * S - Rr, px * S + Rr, py * S + Rr], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i], 0.0)
        text_box(d, sc((lx, ly)), f"{head} {tv:.1f}秒", FM, COL[who], "lm", edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    g = num_ok(rows[f]["gap_m"]); v = num_ok(rows[f]["robot_v"]) or 0.0
    return [f"{vmap[f]:.1f} 秒", f"ハコブくんの速さ {abs(v):.2f} m/秒" + ("（下がる）" if rows[f]["mode"] == "back" else ""),
            "ハコブくんと車いす（人を含む）のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
tmpT = tempfile.mkdtemp(prefix="m271t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("chair", "axle_px", "axle_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        Rr = LW["trail"] * S / 2; td.ellipse([p[0] * S - Rr, p[1] * S - Rr, p[0] * S + Rr, p[1] * S + Rr], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    add_any = np.zeros((H, W), bool)
    for g in (ob[:, :, 0], ob[:, :, 1]): add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 62
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * len(lines) + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"{NAME}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per271_{SHOT}.csv"), "w").write("frame,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る目印の画素 合計", sum(p[1] for p in per))
