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

"""
Read OPEN Medevio requests (požadavky) from local MySQL table `pozadavky`
and export to Excel in the same visual format as Agenda.
"""

import pymysql
import pandas as pd
from datetime import datetime
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
from openpyxl.utils.dataframe import dataframe_to_rows

# ==============================
# 🔧 CONFIGURATION
# ==============================
DB_CONFIG = {
    "host": "192.168.1.76",
    "port": 3307,
    "user": "root",
    "password": "Vlado9674+",
    "database": "medevio",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor,
}

EXPORT_DIR = Path(r"u:\Dropbox\Ordinace\Reporty")
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
xlsx_path = EXPORT_DIR / f"{datetime.now():%Y-%m-%d_%H-%M-%S} Otevřené požadavky.xlsx"

# ==============================
# 📡 LOAD DATA
# ==============================
print("📡 Fetching open requests from MySQL...")

conn = pymysql.connect(**DB_CONFIG)
with conn.cursor() as cur:
    cur.execute("""
        SELECT id AS Request_ID,
               displayTitle AS Title,
               pacient_prijmeni AS Pacient_Prijmeni,
               pacient_jmeno AS Pacient_Jmeno,
               pacient_rodnecislo AS RodneCislo,
               createdAt AS Created,
               updatedAt AS Updated,
               doneAt AS Done,
               removedAt AS Removed
        FROM pozadavky
        WHERE doneAt IS NULL AND removedAt IS NULL
        ORDER BY createdAt DESC
    """)
    rows = cur.fetchall()
conn.close()

if not rows:
    print("⚠️ No open requests found.")
    raise SystemExit()

df = pd.DataFrame(rows)
print(f"✅ Loaded {len(df)} open requests.")

# ==============================
# 🧩 CLEAN + PREPARE
# ==============================
df["Patient"] = (df["Pacient_Prijmeni"].fillna("") + " " + df["Pacient_Jmeno"].fillna("")).str.strip()

df = df.rename(columns={
    "RodneCislo": "Rodné číslo",
    "Request_ID": "Request ID",
})
df = df[["Created", "Title", "Patient", "Rodné číslo", "Request ID", "Updated"]]

# ==============================
# 🧾 EXPORT TO EXCEL
# ==============================
wb = Workbook()
ws = wb.active
ws.title = "Otevřené požadavky"

# === Styles ===
header_fill = PatternFill("solid", fgColor="00FF99")
alt_fill = PatternFill("solid", fgColor="F2FFF2")
thin_border = Border(
    left=Side(style="thin", color="000000"),
    right=Side(style="thin", color="000000"),
    top=Side(style="thin", color="000000"),
    bottom=Side(style="thin", color="000000")
)

# === Write DataFrame ===
for r_idx, row in enumerate(dataframe_to_rows(df, index=False, header=True), start=1):
    ws.append(row)

# === Header styling ===
for col_idx in range(1, len(df.columns) + 1):
    c = ws.cell(row=1, column=col_idx)
    c.font = Font(bold=True)
    c.alignment = Alignment(horizontal="center", vertical="center")
    c.fill = header_fill
    c.border = thin_border
    ws.column_dimensions[get_column_letter(col_idx)].width = 25

# === Data styling ===
for r_idx, row in enumerate(ws.iter_rows(min_row=2, max_row=ws.max_row, max_col=ws.max_column), start=2):
    for cell in row:
        cell.border = thin_border
        if r_idx % 2 == 0:
            cell.fill = alt_fill

ws.freeze_panes = "A2"
wb.save(xlsx_path)

print(f"📘 Exported {len(df)} open requests → {xlsx_path}")
