#!/usr/bin/env python3
"""Проверка наличия таблиц схемы (books, chapters, chapter_analyses, tags, chapter_tags) в Postgres."""
import sys

try:
    import psycopg2
except ImportError:
    print("Установите: pip install psycopg2-binary")
    sys.exit(1)

HOST = "192.168.88.15"
PORT = 5432
USER = "n8n"
PASSWORD = "n8n_password"
DB = "n8n"
EXPECTED = {"books", "chapters", "chapter_analyses", "tags", "chapter_tags"}

try:
    conn = psycopg2.connect(
        host=HOST, port=PORT, user=USER, password=PASSWORD, dbname=DB
    )
    with conn.cursor() as cur:
        cur.execute("""
            SELECT table_name FROM information_schema.tables
            WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
            ORDER BY table_name;
        """)
        found = {row[0] for row in cur.fetchall()}
    conn.close()
    print(f"Postgres {HOST}:{PORT}/{DB}")
    print("Таблицы в public:", ", ".join(sorted(found)) if found else "(нет)")
    missing = EXPECTED - found
    extra = found - EXPECTED
    if not missing:
        print("Ожидаемые таблицы этапа 8: все на месте.")
    else:
        print("Не найдены:", ", ".join(sorted(missing)))
    if extra:
        print("Доп. таблицы:", ", ".join(sorted(extra)))
except Exception as e:
    print(f"Ошибка: {e}")
    sys.exit(1)
