from __future__ import annotations

from sqlalchemy import inspect, text
from sqlalchemy.orm import Session


def has_table(session: Session, table: str) -> bool:
    insp = inspect(session.get_bind())
    return insp.has_table(table)


def has_column(session: Session, table: str, column: str) -> bool:
    if not has_table(session, table):
        return False
    insp = inspect(session.get_bind())
    cols = insp.get_columns(table)
    return any(c["name"] == column for c in cols)


def table_columns(session: Session, table: str) -> list[str]:
    if not has_table(session, table):
        return []
    insp = inspect(session.get_bind())
    return [c["name"] for c in insp.get_columns(table)]


def get_column_listing_default(session: Session, table: str) -> list[str]:
    return table_columns(session, table)


def execute_scalar_int(session: Session, sql: str, params: dict | None = None) -> int:
    row = session.execute(text(sql), params or {}).first()
    if row is None or row[0] is None:
        return 0
    return int(row[0])
