import pymysql
from knihovny.medicus_db import MedicusDB
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
from pathlib import Path
from datetime import datetime
import os

# ==========================================
# CONFIGURATION
# ==========================================
MEDICUS_HOST = "192.168.1.4"
MEDICUS_DB_PATH = r"z:\Medicus 3\data\MEDICUS.FDB"

MYSQL_CONFIG = {
    "host": "192.168.1.76",
    "port": 3307,
    "user": "root",
    "password": "Vlado9674+",
    "database": "medevio",
    "charset": "utf8mb4",
    "autocommit": True
}

# ==========================================
# PATHS
# ==========================================
script_location = Path(__file__).resolve().parent
project_root = script_location.parent
template_dir = project_root / "Templates"
output_dir = script_location / "Output"
output_dir.mkdir(exist_ok=True)

# Font paths
font_regular = (template_dir / "fonts" / "DejaVuSans.ttf").as_uri()
font_bold = (template_dir / "fonts" / "DejaVuSans-Bold.ttf").as_uri()
font_italic = (template_dir / "fonts" / "DejaVuSans-Oblique.ttf").as_uri()

# ==========================================
# INIT CONNECTIONS
# ==========================================
print("Connecting to Medicus...")
medicus = MedicusDB(MEDICUS_HOST, MEDICUS_DB_PATH)

print("Connecting to MySQL...")
mysql = pymysql.connect(
    cursorclass=pymysql.cursors.DictCursor,
    **MYSQL_CONFIG
)

# ==========================================
# FETCH REGISTERED PATIENTS
# ==========================================
print("Fetching registered patients from Medicus...")
patients = medicus.get_active_registered_patients(as_dict=True)

patients_by_rc = {p["rodcis"]: p for p in patients}
print(f"Loaded {len(patients_by_rc)} registered patients")

# ==========================================
# FETCH LAST INSURANCE STATES
# ==========================================
print("Fetching last insurance states from MySQL...")

sql_last_states = """
SELECT rc, stav
FROM (
    SELECT rc, stav,
           ROW_NUMBER() OVER (PARTITION BY rc ORDER BY k_datu DESC) AS rn
    FROM vzp_stav_pojisteni
) t
WHERE rn = 1
"""

with mysql.cursor() as cur:
    cur.execute(sql_last_states)
    last_states = cur.fetchall()

print(f"Loaded {len(last_states)} last insurance states")

# ==========================================
# COMPARE
# ==========================================
suspected = []

for row in last_states:
    rc = row["rc"]
    stav = row["stav"]

    if rc in patients_by_rc and stav != "1":
        p = patients_by_rc[rc]
        suspected.append({
            "rc": rc,
            "prijmeni": p["prijmeni"],
            "jmeno": p["jmeno"],
            "poj": p["poj"],
            "stav": stav
        })

print(f"Nalezeno {len(suspected)} problémových záznamů")

# ==========================================
# CLEANUP DB
# ==========================================
medicus.close()
mysql.close()

# ==========================================
# PDF GENERATION (WEASYPRINT)
# ==========================================
env = Environment(
    loader=FileSystemLoader(str(template_dir)),
    autoescape=True
)

template = env.get_template("vzp_console_report.html")

html_content = template.render(
    patients=suspected,
    generated_at=datetime.now().strftime("%d. %m. %Y %H:%M"),
    font_regular=font_regular,
    font_bold=font_bold,
    font_italic=font_italic
)

timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
pdf_file = output_dir / f"kontrola_pojisteni_{timestamp}.pdf"

print("Generuji PDF přes WeasyPrint...")
HTML(string=html_content, base_url=str(template_dir)).write_pdf(pdf_file)

print("\n✅ PDF REPORT VYTVOŘEN:")
print(pdf_file.resolve())

try:
    os.startfile(pdf_file)
except Exception:
    pass
