from __future__ import annotations

import re
import sqlite3


def next_id(conn: sqlite3.Connection, prefix: str, table: str, *, id_column: str = "id") -> str:
    rows = conn.execute(
        f"SELECT {id_column} FROM {table} WHERE {id_column} GLOB ?",
        (f"{prefix}[0-9]*",),
    ).fetchall()
    max_n = 0
    for r in rows:
        val = r[0] if not hasattr(r, "keys") else r[id_column]
        m = re.match(rf"^{re.escape(prefix)}(\d+)$", str(val))
        if m:
            max_n = max(max_n, int(m.group(1)))
    return f"{prefix}{max_n + 1:03d}"
