# app/src/storage/session.py
 
from __future__ import annotations

from contextlib import contextmanager

import psycopg

from src.core.config import load_settings


def build_dsn() -> str:
    settings = load_settings()
    password_part = settings.db_password.replace("@", "%40")
    return (
        f"postgresql://{settings.db_user}:{password_part}"
        f"@{settings.db_host}:{settings.db_port}/{settings.db_name}"
    )


@contextmanager
def get_connection():
    connection = psycopg.connect(build_dsn(), autocommit=False)
    try:
        yield connection
        connection.commit()
    finally:
        connection.close()


def check_database_health() -> tuple[bool, str]:
    try:
        with get_connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute("SELECT version()")
                row = cursor.fetchone()
                if row is None:
                    return False, "PostgreSQL ping returned no rows."

                version = str(row[0]).strip()
    except Exception as exc:
        return False, f"PostgreSQL error: {exc}"

    return True, version