import fdb, sys
sys.stdout.reconfigure(encoding='utf-8')
conn = fdb.connect(dsn=r'localhost:c:\medicus 3\data\medicus.fdb', user='SYSDBA', password='masterkey', charset='win1250')
cur = conn.cursor()

sql = """
    SELECT nes.id, TRIM(kar.prijmeni) || ', ' || TRIM(kar.jmeno) AS jmeno,
           nes.zacnes,
           (SELECT MAX(h.datum) FROM hpn h
            WHERE h.idnes = nes.id AND h.typ = 'P' AND h.storno = 'F') AS posl_potvrzeni
    FROM nes, kar
    WHERE nes.zacnes <= current_date
      AND nes.konnes IS NULL
      AND nes.idpac = kar.idpac
      AND nes.pracne = 'A'
      AND nes.storno <> 'T'
      AND (
          NOT EXISTS (SELECT id FROM nesd WHERE nesd.idnes = nes.id)
          OR (SELECT FIRST 1 kam FROM nesd WHERE nesd.idnes = nes.id
              ORDER BY nesd.datum DESC, nesd.id DESC) = 'N'
      )
    ORDER BY kar.prijmeni ASC
"""

cur.execute(sql)
for row in cur.fetchall():
    print(row)
conn.close()
