"""Shared helper: a line-item chunk for a resolved row, with the table's row-label column appended."""
import re
from quber.playground.retrieval import RetrievedChunk
LABEL=re.compile(r'<td id="t(\d+)-(\d+)-0">(.*?)</td>')
def row_labels(table_content: str) -> list[tuple[int, str]]:
    out=[]; seen=set()
    for m in LABEL.finditer(table_content):
        r=int(m.group(2)); t=re.sub(r"<[^>]+>","",m.group(3)).strip()
        if r in seen: continue
        seen.add(r); out.append((r,t))
    return out
def row_chunk(conn, doc_id: int, table_id: str, row: int, with_labels: bool = True):
    t=table_id.split("/")[-1]; cid=f"t{t}-line-{row}"
    r=conn.execute("select chunk_id, chunk_type, page, content from ade_playground.chunks where document_id=%s and chunk_id=%s",(doc_id,cid)).fetchone()
    if r is None: return None
    content=r[3]
    if with_labels:
        tc=conn.execute("select content from ade_playground.chunks where document_id=%s and chunk_id=%s",(doc_id,table_id)).fetchone()[0]
        labels=[f"row {n}: {lab}" for n,lab in row_labels(tc) if lab]
        if labels: content += "\n\nThis chunk is ONE row of the table. All rows of that table, for orientation only:\n" + "\n".join(labels)
    return RetrievedChunk(chunk_id=r[0], chunk_type=r[1], page=r[2], content=content, score=0.0, parent_chunk_id=table_id)
