from functions import get_medicus_connection
from functions import get_mysql_connection
from functions import check_insurance
import time, random

def prepare_processed_rcs():
    consql=get_mysql_connection()
    cursql=consql.cursor()

    sql="""
    WITH ranked AS (
      SELECT
        vr.*,
        ROW_NUMBER() OVER (
          PARTITION BY rc
          ORDER BY k_datu DESC, queried_at DESC
        ) AS rn
      FROM vzp_stav_pojisteni AS vr
    )
    SELECT rc
    FROM ranked
    WHERE rn = 1
    """

    cursql.execute(sql)
    rows=cursql.fetchall()
    print(f"Pocet jiz zpracovanych rodnych cisel v MYSQL MEDEVIO je {len(rows)}")
    rc_set_vzp = {row["rc"] for row in rows}
    return (rc_set_vzp)

con=get_medicus_connection()
cur=con.cursor()
cur.execute("select rodcis, prijmeni, jmeno from kar where rodcis starting with '3'")

rc_set_vzp=prepare_processed_rcs()

rows=cur.fetchall()
print(f"Pocet vybranych radku z tabulky KAR je: {len(rows)}")

for row in rows:
    if row[0] in rc_set_vzp:
        continue
    else:
        print(row[0], row[1],row[2])
        print(check_insurance(row[0]))
        time.sleep(random.uniform(1, 5))
