from dataclasses import dataclass
from typing import Mapping


@dataclass(frozen=True)
class PostgresConfig:
    host: str
    port: int
    username: str
    password: str
    database: str
    driver: str = "psycopg2"
    pool_size: int = 3
    max_overflow: int = 5
    pool_pre_ping: bool = True
    pool_recycle: int = 300

    def url(self) -> str:
        return (
            f"postgresql+{self.driver}://"
            f"{self.username}:{self.password}@{self.host}:{self.port}/{self.database}"
        )

    @classmethod
    def from_env(cls, env: Mapping[str, str]) -> "PostgresConfig":
        return cls(
            host=env["POSTGRES_HOST"],
            port=int(env["POSTGRES_PORT"]),
            username=env["POSTGRES_USERNAME"],
            password=env["POSTGRES_PASSWORD"],
            database=env["POSTGRES_DATABASE"],
            driver=env.get("POSTGRES_DRIVER", "psycopg2"),
        )
