import json
import os

import typer

app = typer.Typer(help="PostgreSQL utilities")


def get_connection():
    try:
        import psycopg
    except ImportError:
        raise typer.Exit("psycopg not installed. Run: uvx 'adaptivegears[pg]' pg ...")

    url = os.environ.get("DATABASE_URL")
    if not url:
        raise typer.Exit("DATABASE_URL environment variable not set")

    return psycopg.connect(url)


@app.command("list")
def list_tables(
    schema: str = typer.Option("public", "--schema", "-s", help="Schema to list tables from"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
):
    """List tables in the database."""
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT table_name
                FROM information_schema.tables
                WHERE table_schema = %s
                  AND table_type = 'BASE TABLE'
                ORDER BY table_name
                """,
                (schema,),
            )
            tables = [row[0] for row in cur.fetchall()]

    if json_output:
        print(json.dumps(tables))
    else:
        for table in tables:
            print(table)
