# %% [markdown]
# # View Tables — qc_trace prod database
# Quick inspection of all tables, row counts, and sample rows.
# Secrets loaded from `.prod.env` via `dotenv` — never printed.

# %%
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from utils.connection import init, query_df
from IPython.display import display, Markdown

conn = init()
display(Markdown("**Connected.**"))

# %% [markdown]
# ## 1 — Table row counts

# %%
def show_table_row_counts():
    return query_df(conn, """
        SELECT relname AS table_name, n_live_tup AS est_rows
        FROM   pg_stat_user_tables
        ORDER  BY n_live_tup DESC
    """)

display(show_table_row_counts())

# %% [markdown]
# ## 2 — Column details per table

# %%
TABLES = [
    "sessions", "messages", "token_usage", "tool_calls",
    "tool_results", "file_progress", "schema_version", "version_config",
]

def show_columns(table: str):
    display(Markdown(f"### {table}"))
    display(query_df(conn, """
        SELECT column_name, data_type, is_nullable
        FROM   information_schema.columns
        WHERE  table_name = %s
        ORDER  BY ordinal_position
    """, (table,)))

for t in TABLES:
    show_columns(t)

# %% [markdown]
# ## 3 — Sample rows (5 per table)

# %%
def show_sample(table: str, limit: int = 5):
    assert table in TABLES
    display(Markdown(f"### {table}"))
    display(query_df(conn, f"SELECT * FROM {table} LIMIT %s", (limit,)))  # noqa: S608

for t in TABLES:
    show_sample(t)

# %% [markdown]
# ## 4 — Index overview

# %%
def show_indexes():
    return query_df(conn, """
        SELECT indexname, tablename, indexdef
        FROM   pg_indexes
        WHERE  schemaname = 'public'
        ORDER  BY tablename, indexname
    """)

display(show_indexes())

# %% [markdown]
# ---
# *End of notebook.*
