from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path


def load_local_dotenv(path: Path = Path(".env")) -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key and key not in os.environ:
            os.environ[key] = value


@dataclass(frozen=True)
class DatabaseSettings:
    host: str
    port: int
    database: str
    user: str
    password: str | None
    sslmode: str | None

    @classmethod
    def from_env(cls) -> "DatabaseSettings":
        load_local_dotenv()
        return cls(
            host=os.getenv("DB_HOST", "192.168.0.112"),
            port=int(os.getenv("DB_PORT", "4200")),
            database=os.getenv("DB_NAME", "postgres"),
            user=os.getenv("DB_USER", "kun"),
            password=os.getenv("DB_PASSWORD", "nxY7HUoJYjUgn"),
            sslmode=os.getenv("DB_SSLMODE") or None,
        )

    def connect_kwargs(self) -> dict[str, object]:
        kwargs: dict[str, object] = {
            "host": self.host,
            "port": self.port,
            "dbname": self.database,
            "user": self.user,
        }
        if self.password:
            kwargs["password"] = self.password
        if self.sslmode:
            kwargs["sslmode"] = self.sslmode
        return kwargs


@dataclass(frozen=True)
class AppSettings:
    database: DatabaseSettings
    schema: str

    @classmethod
    def from_env(cls) -> "AppSettings":
        return cls(
            database=DatabaseSettings.from_env(),
            schema=os.getenv("DB_SCHEMA", "bid"),
        )


def get_settings() -> AppSettings:
    return AppSettings.from_env()
