"""
Vérifie que .env est bien chargé et que la connexion PostGIS fonctionne.

Usage :
    python scripts/check_env.py

Équivalent, côté eau, des scripts de diagnostic du POC foncier
(scripts/print_agency_scope.py, scripts/refresh_*.py).
"""

from __future__ import annotations

import sys
from pathlib import Path

# Permet d'exécuter le script depuis scripts/ sans installer le paquet
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from config import Config  # noqa: E402
from services.db import get_connection  # noqa: E402


def main() -> int:
    print("=== Configuration chargée depuis .env ===")
    print(f"Schéma applicatif      : {Config.SCHEMA}")
    print(f"Périmètre EPCI (scope) : {Config.EPCI_SCOPE}")
    print(f"Année prélèvements     : {Config.ANNEE_PRELEVEMENTS}")
    print(f"Année prix              : {Config.ANNEE_PRIX}")
    print(f"PGHOST                  : {Config.DB_HOST}")
    print(f"PGPORT                  : {Config.DB_PORT}")
    print(f"PGDATABASE              : {Config.DB_NAME or '(non renseigné)'}")
    print(f"PGUSER                  : {Config.DB_USER or '(non renseigné)'}")
    print()

    if not Config.pg_configured():
        print("⚠️  PGDATABASE / PGUSER manquants : copiez .env.example vers .env"
              " et complétez les informations de connexion.")
        return 1

    print("=== Test de connexion PostgreSQL / PostGIS ===")
    try:
        conn = get_connection()
        with conn, conn.cursor() as cur:
            cur.execute("SELECT version();")
            (version,) = cur.fetchone()
            print(f"✅ Connexion OK : {version}")

            cur.execute(
                "SELECT table_name FROM information_schema.tables "
                "WHERE table_schema = %s ORDER BY table_name;",
                (Config.SCHEMA,),
            )
            tables = [row[0] for row in cur.fetchall()]
            print(f"\nTables trouvées dans le schéma '{Config.SCHEMA}' ({len(tables)}) :")
            for name in tables:
                print(f"  - {name}")
        return 0
    except Exception as exc:  # pragma: no cover - diagnostic manuel
        print(f"❌ Échec de connexion : {exc}")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
