"""Two containers write to the same table at the same time.
Usage: concurrent_write.py <writer-name> <batches> <append|upsert>
append: each writer adds new rows. upsert: both writers merge_insert the same 5 ids."""
import sys
import time

from common import connect, TABLE, read_chunks, to_record

writer, batches, mode = sys.argv[1], int(sys.argv[2]), sys.argv[3]
prefix = sys.argv[4] if len(sys.argv) > 4 else "shared"
rows, _, _ = read_chunks()
base = to_record(rows[0])
table = connect().open_table(TABLE)
ok = failed = 0
t_start = time.time()
for i in range(batches):
    try:
        if mode == "append":
            table.add([dict(base, id=f"{writer}-{i}-{j}") for j in range(5)])
        else:
            recs = [dict(base, id=f"{prefix}-{j}", text=f"{writer} batch {i}") for j in range(5)]
            table.merge_insert("id").when_matched_update_all().when_not_matched_insert_all().execute(recs)
        ok += 1
    except Exception as e:
        failed += 1
        print(f"[{writer}] batch {i} failed: {type(e).__name__}: {str(e)[:300]}")
    time.sleep(0.02)
print(f"[{writer}] {mode}: {ok} batches ok, {failed} failed, window {t_start % 1000:.1f}s to {time.time() % 1000:.1f}s (epoch mod 1000)")
