#!/usr/bin/env python3
"""依頼 392: session_392.sh --dry-fake で run_so101_policy.py の代わりに流す (アーム・カメラ・サーバーなし).

fake_client_373.py と同じ形 (同じ引数を受け, 同じ聞き方で結果を聞き, 同じ台帳に 1 行) だが, 1 回の流れは
run_so101_policy.py の run (--handover-above-mm の始めの道 → 渡す所 → 推論のループ run_trial) をそのまま通す.
差し替えるのは 次の 4 つだけ:
  - フォロワー・カメラ (DryArm): 送った値をそのまま今の角度にする (始めは休みの姿勢の中心. DryArm と同じ).
    机・手首のカメラの絵は so101f の実機の試し (so101_Log12 の台帳の so101f の行) のうち 同じ場所の 1 回目の
    最初のコマ (動画のない回は飛ばす. KIOXIA の記録は読むだけ. 写しを --cache に置く). ブロックの読み (yaw_lib_343.read_block) は実物の絵で通る
  - サーバー (Policy の client): 答え (30, 6) = 今の角度から 関節 5 つを 1 コマ 0.1° ずつ 肘を伸ばす向きへ (仮の値)・爪はそのまま.
    答えが返るまで --fake-latency 秒 (既定 0.45) 待つ
  - キー (KeyReader): 推論のループに入ってから --fake-model-frames コマ (既定 60) で q
  - 記録の作業用の写し (LOCAL_RUNS): --cache の下 (~/so101_runs には書かない)
KIOXIA (/Volumes/) には書かない (--log-dir が /Volumes/ の下なら止める). --execute は受けない.
"""
import argparse
import csv
import sys
import time
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
sys.path.insert(0, str(HERE))
import run_so101_policy as R  # noqa: E402

LOG12 = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12")
CACHE = Path("/tmp/r392_dry/cache")


def first_frames(place, cache=CACHE, log=LOG12):
    """so101f の実機の試しのうち 場所 place の 1 回目の 最初のコマ (机・手首. RGB 480×640). 写しがあればそれを読む"""
    from PIL import Image
    cache.mkdir(parents=True, exist_ok=True)
    out = {c: cache / f"place{place}_{c}.png" for c in R.CAMERAS}
    if not all(p.exists() for p in out.values()):
        import av
        with open(log / R.TRIALS_CSV, newline="") as f:
            rows = [dict(zip(R.TRIAL_COLUMNS, r)) for r in list(csv.reader(f))[1:]]
        vid = "videos/observation.images.{}/chunk-000/file-000.mp4"
        rows = [r for r in rows if r["model"].startswith("so101f") and r["place"] == str(place) and r["execute"] == "1"
                and all((Path(r["record_dir"]) / vid.format(c)).exists() for c in R.CAMERAS)]      # 動画のない回 (止めた回) は飛ばす
        if not rows:
            raise FileNotFoundError(f"so101f の場所{place} の試し (動画あり) が台帳にない")
        src = Path(rows[0]["record_dir"])
        for c in R.CAMERAS:
            with av.open(str(src / vid.format(c))) as v:
                img = next(v.decode(video=0)).to_ndarray(format="rgb24")
            Image.fromarray(img).save(out[c])
        (cache / f"place{place}_source.txt").write_text(f"{src}\n")
    return {c: np.asarray(Image.open(p).convert("RGB")) for c, p in out.items()}


class FakeArm:
    def __init__(self, images):
        import lerobot_safe_259 as safe
        self.state = np.array([safe.load_rest_pose()[0][m] for m in R.MOTORS], dtype=np.float64)
        self.last_sent = self.state.copy()
        self.images = images
        self.leader = None
        self.n_sent = 0

    def observe(self):
        return self.state.copy(), self.images["desk"], self.images["wrist"]

    def send(self, target):
        self.state = np.asarray(target, dtype=np.float64).copy()
        self.last_sent = self.state.copy()
        self.n_sent += 1
        return self.last_sent

    def leader_target(self):
        return None

    def close(self):
        pass


class FakeClient:
    def __init__(self, latency, counter):
        self.latency, self.counter = latency, counter

    def infer(self, obs):
        time.sleep(self.latency)
        self.counter["queries"] += 1
        s = np.asarray(obs["observation/state"], dtype=np.float64)
        d = np.zeros(6)
        d[2] = -0.1                         # 肘を 1 コマ 0.1° 伸ばす (仮の値)
        return {"actions": np.stack([s + d * (k + 1) for k in range(30)]).astype(np.float32)}

    def close(self):
        pass


class FakeKeys:
    """推論のループに入ってから (サーバーに 1 回問い合わせてから) n コマで q"""

    def __init__(self, counter, n):
        self.counter, self.n, self.polls = counter, n, 0

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

    def start(self):
        pass

    def poll(self):
        if self.counter["queries"] == 0:
            return None
        self.polls += 1
        return "q" if self.polls >= self.n else None


def main(argv=None):
    argv = list(sys.argv[1:] if argv is None else argv)
    ap = argparse.ArgumentParser(add_help=False)
    ap.add_argument("--log-dir", required=True)
    ap.add_argument("--place", type=int, required=True)
    ap.add_argument("--execute", action="store_true")
    ap.add_argument("--fake-latency", type=float, default=0.45)
    ap.add_argument("--fake-model-frames", type=int, default=60)
    ap.add_argument("--cache", default=str(CACHE))
    a, rest = ap.parse_known_args(argv)
    log_dir = Path(a.log_dir).resolve()
    if str(log_dir).startswith("/Volumes/"):
        sys.exit(f"[ERROR] --dry-fake は KIOXIA に書かない: {log_dir}")
    if a.execute:
        sys.exit("[ERROR] fake_run_392.py に --execute は渡さない")
    cache = Path(a.cache)
    images = first_frames(a.place, cache)
    counter = {"queries": 0}
    base_policy = R.Policy
    R.DryArm = lambda: FakeArm(images)
    R.Policy = lambda port: base_policy(port, client=FakeClient(a.fake_latency, counter))
    R.KeyReader = lambda: FakeKeys(counter, a.fake_model_frames)
    R.LOCAL_RUNS = cache.parent / "so101_runs"
    print(f"[FAKE  ] run_so101_policy.py をアーム・カメラ・サーバーなしで流す. 場所 {a.place} の絵は "
          f"{(cache / f'place{a.place}_source.txt').read_text().strip()} の最初のコマ. 答えが返るまで {a.fake_latency:g} 秒・"
          f"推論のループに入って {a.fake_model_frames} コマで q")
    return R.main(rest + ["--log-dir", str(log_dir), "--place", str(a.place)])


if __name__ == "__main__":
    sys.exit(main())
