# SPDX-License-Identifier: LGPL-3.0-or-later

import os
from pyqt6_scaffold.core.logging import setup_logger
from pyqt6_scaffold.core.database import AbstractDatabase

log = setup_logger(__name__)

class PostgresqlDatabase(AbstractDatabase):
    """
    AbstractDatabase implementation for PostgreSQL via psycopg2.

    Configuration is read from environment variables:
        PG_HOST, PG_PORT, PG_USER, PG_DATABASE, PG_PASSWORD

    Requires:
        pip install pyqt6-scaffold[postgres]
    """
    @property
    def placeholder(self) -> str:
        return "%s"

    def _connect(self):
        try:
            import psycopg2 as pg
        except ImportError:
            log.error("Ошибка импорта psycopg2")
            raise

        DB_CONFIG = {
            "host": os.getenv("PG_HOST", "127.0.0.1"),
            "port": int(os.getenv("PG_PORT", 5432)),
            "user": os.getenv("PG_USER", "postgres"),
            "database": os.getenv("PG_DATABASE", "postgres"),
            "password": os.getenv("PG_PASSWORD", "postgres")
        }

        return pg.connect(**DB_CONFIG)

class MysqlDatabase(AbstractDatabase):
    """
    AbstractDatabase implementation for MySQL via pymysql.

    Configuration is read from environment variables:
        MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_DATABASE, MYSQL_PASSWORD

    Requires:
        pip install pyqt6-scaffold[mysql]
    """
    @property
    def placeholder(self) -> str:
        return "%s"

    def _connect(self):
        try:
            import pymysql as pms
        except ImportError:
            log.error("Ошибка импорта pymysql")
            raise

        DB_CONFIG = {
            "host": os.getenv("MYSQL_HOST", "localhost"),
            "port": int(os.getenv("MYSQL_PORT", 3306)),
            "user": os.getenv("MYSQL_USER", "root"),
            "database": os.getenv("MYSQL_DATABASE", "root"),
            "password": os.getenv("MYSQL_PASSWORD", "root")
        }

        return pms.connect(**DB_CONFIG)

class SqliteDatabase(AbstractDatabase):
    """
    AbstractDatabase implementation for SQLite via the stdlib sqlite3 module.

    Configuration is read from environment variables:
        SQLITE_PATH  (default: app.db)

    No additional dependencies required.
    """
    @property
    def placeholder(self) -> str:
        return "?"

    def _connect(self):
        import sqlite3
        path = os.getenv("SQLITE_PATH", "app.db")
        return sqlite3.connect(path)