import sqlite3
from pathlib import Path


def _connect(db_path: Path) -> sqlite3.Connection:
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    return conn


def _list_tables(conn: sqlite3.Connection) -> list[str]:
    cur = conn.execute(
        "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
    )
    return [r["name"] for r in cur.fetchall()]


def _table_columns(conn: sqlite3.Connection, table: str) -> list[tuple[int, str, str, int, str, int]]:
    cur = conn.execute(f"PRAGMA table_info({table})")
    rows = cur.fetchall()
    return [(r[0], r[1], r[2], r[3], r[4], r[5]) for r in rows]


def inspect(db_path: Path, tables: list[str] | None = None) -> None:
    print(f"\n=== {db_path} ===")
    if not db_path.exists():
        print("NOT FOUND")
        return
    conn = _connect(db_path)
    try:
        all_tables = _list_tables(conn)
        print(f"tables={len(all_tables)}")
        if tables is None:
            tables = all_tables
        for t in tables:
            if t not in all_tables:
                print(f"\n-- {t} (missing)")
                continue
            cols = _table_columns(conn, t)
            print(f"\n-- {t} cols={len(cols)}")
            for cid, name, ctype, notnull, dflt, pk in cols:
                print(f"{cid:>3}  {name:<40} {ctype:<12} notnull={notnull} pk={pk} dflt={dflt}")
    finally:
        conn.close()


if __name__ == "__main__":
    base_dir = Path(__file__).resolve().parents[1]
    l2 = base_dir / "database" / "L2" / "L2.db"
    l3 = base_dir / "database" / "L3" / "L3.db"
    web = base_dir / "database" / "Web" / "Web_App.sqlite"

    inspect(
        l3,
        tables=[
            "dm_player_features",
            "dm_player_match_history",
            "dm_player_map_stats",
            "dm_player_weapon_stats",
        ],
    )
    inspect(web)
    inspect(l2, tables=["dim_players", "fact_matches", "fact_match_players", "fact_match_rounds"])
