import socket
import fdb


def get_medicus_connection():
    """
    Připojí se k Firebird medicus.fdb podle názvu počítače.
    Vrátí fdb.Connection nebo vyhodí RuntimeError pro neznámý počítač.
    """
    computer_name = socket.gethostname().upper()
    dsn_map = {
        "LEKAR":  r"localhost:M:\medicus\data\medicus.fdb",
        "SESTRA": r"192.168.1.10:m:\medicus\data\medicus.fdb",
        "LENOVO": r"192.168.1.10:m:\medicus\data\medicus.fdb",
    }
    dsn = dsn_map.get(computer_name, r"localhost:c:\medicus 3\data\medicus.fdb")
    print(f"[medicus_db] Připojuji se jako {computer_name} → {dsn}")
    return fdb.connect(dsn=dsn, user="SYSDBA", password="masterkey", charset="win1250")


def get_medicus_db():
    """Vrátí MedicusDB instanci s připojením podle názvu počítače."""
    conn = get_medicus_connection()
    instance = object.__new__(MedicusDB)
    instance.conn = conn
    instance.cur = conn.cursor()
    return instance


class MedicusDB:

    def __init__(self, host, db_path, user="SYSDBA", password="masterkey", charset="WIN1250"):
        self.conn = fdb.connect(
            host=host,
            database=db_path,
            user=user,
            password=password,
            charset=charset
        )
        self.cur = self.conn.cursor()

    def get_fak_kapitace(self, as_dict=False):
        sql = """
        SELECT
            fak.id,
            fak.cisfak,
            fak.poj,
            fak.kapdetail
        FROM fak
        WHERE fak.kapdetail IS NOT NULL
          AND fak.kapdetail <> ''
        """
        if as_dict:
            return self.query_dict(sql)
        return self.query(sql)

    def query(self, sql, params=None):
        self.cur.execute(sql, params or ())
        return self.cur.fetchall()

    def query_dict(self, sql, params=None):
        self.cur.execute(sql, params or ())
        cols = [d[0].strip().lower() for d in self.cur.description]
        return [dict(zip(cols, row)) for row in self.cur.fetchall()]

    def get_active_registered_patients(self, as_dict=False):
        sql = """
        SELECT
            kar.rodcis,
            kar.prijmeni,
            kar.jmeno,
            kar.poj
        FROM kar
        WHERE kar.vyrazen = 'N'
          AND kar.rodcis IS NOT NULL
          AND kar.rodcis <> ''
          AND EXISTS (
              SELECT r.id FROM registr r
              JOIN icp i ON r.idicp = i.idicp
              WHERE r.idpac = kar.idpac
                AND r.datum <= CURRENT_DATE
                AND (r.datum_zruseni IS NULL OR r.datum_zruseni >= CURRENT_DATE)
                AND r.priznak IN ('V','D','A')
                AND i.icp = '09305001'
                AND i.odb = '001'
          )
        ORDER BY kar.prijmeni, kar.rodcis
        """
        if as_dict:
            return self.query_dict(sql)
        return self.query(sql)

    def get_all_patients(self, as_dict=False):
        sql = """
        SELECT
            kar.rodcis,
            kar.prijmeni,
            kar.jmeno,
            kar.poj
        FROM kar
        """
        if as_dict:
            return self.query_dict(sql)
        return self.query(sql)

    def close(self):
        self.conn.close()
