"""Clone the app-written rows of each worktree thread until the database holds TOTAL threads.

Usage: python3 -I clone.py <statev2.sqlite> <total> <archived>
"""
import json
import sqlite3
import sys

db, total, archived = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
con = sqlite3.connect(db)
con.row_factory = sqlite3.Row
tables = [
    r[0]
    for r in con.execute(
        "select name from sqlite_schema where type='table' and name like 'orchestration_v2_projection_%'"
    )
    if con.execute(f"select count(*) from pragma_table_info('{r[0]}') where name='thread_id'").fetchone()[0]
    # Filled by a trigger on turn items.
    and r[0] != "orchestration_v2_projection_turn_item_counts"
]
sources = [
    r[0]
    for r in con.execute(
        "select thread_id from orchestration_v2_projection_threads "
        "where json_extract(payload_json,'$.worktreePath') is not null order by thread_id"
    )
]
rows = {t: {s: [dict(r) for r in con.execute(f"select * from {t} where thread_id=?", (s,))] for s in sources} for t in tables}
ids = {}
for s in sources:
    found = set()
    for t in tables:
        for r in rows[t][s]:
            for k, v in r.items():
                if k.endswith("_id") and k != "project_id" and isinstance(v, str) and len(v) > 8:
                    found.add(v)
    ids[s] = sorted(found, key=len, reverse=True)

existing = con.execute("select count(*) from orchestration_v2_projection_threads").fetchone()[0]
copies = total - existing
con.execute("begin")
for n in range(copies):
    s = sources[n % len(sources)]
    suffix = f"-c{n}"

    def fix(v):
        if not isinstance(v, str):
            return v
        for i in ids[s]:
            v = v.replace(i, i + suffix)
        return v

    for t in tables:
        for r in rows[t][s]:
            out = {k: fix(v) for k, v in r.items()}
            if t == "orchestration_v2_projection_threads":
                payload = json.loads(out["payload_json"])
                payload["worktreePath"] = payload["worktreePath"] + suffix
                payload["branch"] = (payload.get("branch") or "t3/x") + suffix
                is_archived = n < archived
                if is_archived:
                    out["archived_at"] = r["updated_at"]
                    payload["archivedAt"] = r["updated_at"]
                out["payload_json"] = json.dumps(payload)
            cols = ",".join(out)
            con.execute(
                f"insert into {t} ({cols}) values ({','.join('?' * len(out))})", list(out.values())
            )
con.commit()
print("threads", con.execute("select count(*) from orchestration_v2_projection_threads").fetchone()[0])
print(
    "archived",
    con.execute("select count(*) from orchestration_v2_projection_threads where archived_at is not null").fetchone()[0],
)
print("turn items", con.execute("select count(*) from orchestration_v2_projection_turn_items").fetchone()[0])
