#!/usr/bin/env python3
"""Cut a keyrec session (WAV + CSV) into one-keystroke clips.

    python3 cut_clips.py keyrec-XXXX.wav keyrec-XXXX.csv --split train
    python3 cut_clips.py keyrec-YYYY.wav keyrec-YYYY.csv --split test

train -> train/0001.wav ... and train.csv         (file,key)
test  -> test/0001.wav ...  and test_answers.csv  (file,key)

Rows with keep=0 are skipped. Running again with the same --split appends
clips with continued numbering, so several sessions can be merged.
Standard library only.
"""
import argparse
import array
import csv
import os
import sys
import wave


def read_wav(path):
    with wave.open(path, "rb") as w:
        if w.getnchannels() != 1 or w.getsampwidth() != 2:
            sys.exit(f"{path}: expected 16-bit mono WAV")
        sr = w.getframerate()
        x = array.array("h")
        x.frombytes(w.readframes(w.getnframes()))
    if sys.byteorder == "big":
        x.byteswap()
    return x, sr


def write_wav(path, x, sr):
    y = array.array("h", x)
    if sys.byteorder == "big":
        y.byteswap()
    with wave.open(path, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(sr)
        w.writeframes(y.tobytes())


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("wav")
    p.add_argument("csv")
    p.add_argument("--split", choices=["train", "test"], required=True)
    p.add_argument("--out", default=".", help="output directory (default: .)")
    p.add_argument("--pre", type=float, default=0.02, help="seconds before t_sound (default 0.02)")
    p.add_argument("--post", type=float, default=0.18, help="seconds after t_sound (default 0.18)")
    p.add_argument("--all", action="store_true", help="ignore the keep column")
    a = p.parse_args()

    x, sr = read_wav(a.wav)
    with open(a.csv, newline="") as f:
        rows = list(csv.DictReader(f))

    clip_dir = os.path.join(a.out, a.split)
    index_path = os.path.join(a.out, "train.csv" if a.split == "train" else "test_answers.csv")
    os.makedirs(clip_dir, exist_ok=True)

    existing = []
    if os.path.exists(index_path):
        with open(index_path, newline="") as f:
            existing = list(csv.DictReader(f))
    n = max((int(os.path.splitext(os.path.basename(r["file"]))[0]) for r in existing), default=0)

    pre, length = round(a.pre * sr), round((a.pre + a.post) * sr)
    added, skipped = [], 0
    for r in rows:
        if (not a.all and r["keep"] != "1") or not r["t_sound"]:
            skipped += 1
            continue
        start = round(float(r["t_sound"]) * sr) - pre
        if start < 0 or start + length > len(x):
            skipped += 1
            continue
        n += 1
        name = f"{n:04d}.wav"
        write_wav(os.path.join(clip_dir, name), x[start:start + length], sr)
        added.append({"file": f"{a.split}/{name}", "key": r["key"]})

    with open(index_path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["file", "key"])
        w.writeheader()
        w.writerows(existing + added)

    print(f"{len(added)} clips -> {clip_dir}/ ({skipped} skipped), index: {index_path} ({len(existing) + len(added)} rows)")


if __name__ == "__main__":
    main()
