#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import logging
from knihovny.medicus_db import MedicusDB
from vzpb2b_client import VZPB2BClient
import pymysql
from datetime import date

# ==========================================
# LOGGING SETUP
# ==========================================
logging.basicConfig(
    filename="insurance_check.log",
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    encoding="utf-8"
)

console = logging.getLogger("console")
console.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(message)s"))
console.addHandler(handler)

def log_info(msg):
    logging.info(msg)
    console.info(msg)

def log_error(msg):
    logging.error(msg)
    console.error(msg)

# ==========================================
# MYSQL CONNECTION
# ==========================================
mysql = pymysql.connect(
    host="192.168.1.76",
    port=3307,
    user="root",
    password="Vlado9674+",
    database="medevio",
    charset="utf8mb4",
    autocommit=True
)

def save_insurance_status(mysql_conn, rc, k_datu, result, xml_text):
    sql = """
    INSERT INTO vzp_stav_pojisteni
        (rc, k_datu, stav, kod_pojistovny, nazev_pojistovny,
         pojisteni_kod, stav_vyrizeni, response_xml)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
    """
    try:
        with mysql_conn.cursor() as cur:
            cur.execute(sql, (
                rc,
                k_datu,
                result["stav"],
                result["kodPojistovny"],
                result["nazevPojistovny"],
                result["pojisteniKod"],
                result["stavVyrizeni"],
                xml_text
            ))
    except Exception as e:
        log_error(f"❌ MYSQL ERROR for RC {rc}: {e}")
        log_error(f"---- RAW XML ----\n{xml_text}\n-----------------")
        raise


# ==========================================
# CONFIGURATION
# ==========================================
HOST = "192.168.1.4"
DB_PATH = r"z:\Medicus 3\data\MEDICUS.FDB"

PFX_PATH = r"MBcert.pfx"
PFX_PASSWORD = "Vlado7309208104++"

ENV = "prod"
ICZ = "00000000"
DIC = "00000000"

# ==========================================
# INIT CONNECTIONS
# ==========================================
db = MedicusDB(HOST, DB_PATH)
vzp = VZPB2BClient(ENV, PFX_PATH, PFX_PASSWORD, icz=ICZ, dic=DIC)

# ==========================================
# FETCH REGISTERED PATIENTS
# ==========================================
patients = db.get_active_registered_patients()
log_info(f"Checking {len(patients)} registered patients...\n")

k_datu = date.today().isoformat()

# ==========================================
# LOOP ONE PATIENT PER SECOND
# ==========================================
for rodcis, prijmeni, jmeno, poj in patients:

    log_info(f"=== Checking {prijmeni} {jmeno} ({rodcis}) ===")

    xml = vzp.stav_pojisteni(rc=rodcis, k_datu=k_datu)

    # 1) Check if response looks like XML
    if not xml.strip().startswith("<"):
        log_error(f"❌ INVALID XML for RC {rodcis}")
        log_error(f"---- RAW RESPONSE ----\n{xml}\n----------------------")
        time.sleep(2)
        continue

    # 2) Try parsing XML
    try:
        result = vzp.parse_stav_pojisteni(xml)
    except Exception as e:
        log_error(f"❌ XML PARSE ERROR for RC {rodcis}: {e}")
        log_error(f"---- RAW RESPONSE ----\n{xml}\n----------------------")
        time.sleep(2)
        continue

    log_info(f"Result: {result}")

    # 3) Save into MySQL (with logging)
    try:
        save_insurance_status(mysql, rodcis, k_datu, result, xml)
    except Exception:
        log_error(f"❌ FAILURE inserting to MySQL for {rodcis}")
        continue

    time.sleep(2)

db.close()
log_info("\nDONE.")
