"""公共工具：psycopg v3 连接参数 + 友好打印。

依赖：pip install "psycopg[binary]"
所有脚本统一使用这里的 `conninfo()` / `connect()` 以便集中修改连接参数。
"""
from __future__ import annotations

import os
from contextlib import contextmanager
from typing import Iterable, Sequence

import psycopg


def conninfo() -> str:
    """返回连接串。支持环境变量覆盖（便于 CI / 容器环境）。"""
    host = os.getenv("PGHOST", "127.0.0.1")
    port = os.getenv("PGPORT", "5432")
    db   = os.getenv("PGDATABASE", "learn_pg")
    user = os.getenv("PGUSER", "postgres")
    pwd  = os.getenv("PGPASSWORD", "")
    parts = [f"host={host}", f"port={port}", f"dbname={db}", f"user={user}"]
    if pwd:
        parts.append(f"password={pwd}")
    return " ".join(parts)


@contextmanager
def connect():
    """with connect() as conn: ..."""
    with psycopg.connect(conninfo(), autocommit=False) as conn:
        yield conn


def print_table(rows: Sequence[Sequence], headers: Iterable[str]) -> None:
    """极简表格打印，避免额外依赖 tabulate。"""
    headers = list(headers)
    str_rows = [[("" if v is None else str(v)) for v in r] for r in rows]
    widths = [len(h) for h in headers]
    for r in str_rows:
        for i, v in enumerate(r):
            if i < len(widths):
                widths[i] = max(widths[i], len(v))
    line = "+" + "+".join("-" * (w + 2) for w in widths) + "+"
    print(line)
    print("| " + " | ".join(h.ljust(widths[i]) for i, h in enumerate(headers)) + " |")
    print(line)
    for r in str_rows:
        print("| " + " | ".join(r[i].ljust(widths[i]) for i in range(len(widths))) + " |")
    print(line)


def section(title: str) -> None:
    bar = "=" * 72
    print("\n" + bar)
    print(f"  {title}")
    print(bar)
