import socket
import sys
import pymysql


def _print(msg):
    print(msg, file=sys.stdout, flush=True) if sys.stdout.encoding and sys.stdout.encoding.lower() in ("utf-8", "utf8") \
        else print(msg.encode("utf-8", errors="replace").decode("ascii", errors="replace"), flush=True)

_LOCAL_HOSTS = {"lekar", "sestra", "lenovo"}


def connect_mysql(user="root", password="Vlado9674+", database="medevio",
                  port=3306, charset="utf8mb4", autocommit=True, cursorclass=None):
    """
    Připojí se k MySQL. Na lokálních stanicích (lekar/sestra/lenovo) použije
    127.0.0.1 přímo, jinak zkusí 192.168.1.76 a pak 127.0.0.1 jako fallback.
    Vrátí aktivní pymysql spojení nebo vyhodí RuntimeError.
    """
    hostname = socket.gethostname().lower()
    candidates = ("127.0.0.1",) if hostname in _LOCAL_HOSTS else ("192.168.1.76", "127.0.0.1")

    params = dict(port=port, user=user, password=password,
                  database=database, charset=charset, autocommit=autocommit)
    if cursorclass is not None:
        params["cursorclass"] = cursorclass

    last_error = None
    for host in candidates:
        try:
            conn = pymysql.connect(host=host, **params)
            _print(f"[mysql_db] Pripojeno pres {host} (hostname: {hostname})")
            return conn
        except Exception as e:
            _print(f"[mysql_db] {host} selhal: {e}")
            last_error = e

    raise RuntimeError(f"MySQL nedostupne na zadne adrese. Posledni chyba: {last_error}")
