"""PostgreSQL external data-source adapter."""

from app.core.data_source.adapters.base import BaseDataSourceAdapter
from app.core.data_source.errors import DataSourceConfigurationInvalid


class PostgreSQLAdapter(BaseDataSourceAdapter):
    database_type = "postgresql"
    drivername = "postgresql+psycopg2"
    allowed_tls_options = frozenset(
        {"sslmode", "sslrootcert", "sslcert", "sslkey"}
    )
    certificate_options = frozenset({"sslrootcert", "sslcert", "sslkey"})
    _SSL_MODES = {
        "disable",
        "allow",
        "prefer",
        "require",
        "verify-ca",
        "verify-full",
    }

    def _validate_scalar_option(self, key, value):
        normalized = str(value).strip().lower()
        if key == "sslmode" and normalized not in self._SSL_MODES:
            raise DataSourceConfigurationInvalid("sslmode is invalid")
        return normalized

    def connect_args(self, definition, credential, query_timeout):
        timeout = int(query_timeout)
        options = {
            "connect_timeout": 5,
            "keepalives": 1,
            "keepalives_idle": 30,
            "keepalives_interval": 10,
            "keepalives_count": 3,
            "application_name": "dataops-platform-datasource",
            "options": f"-c statement_timeout={timeout * 1000}",
        }
        options.update(self.validate_options(definition.tls_options))
        return options
