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

import pandas as pd
import pymysql
from datetime import datetime, timedelta

# ================================
# ⚙️ CONFIGURATION
# ================================
DB_CONFIG = {
    "host": "192.168.1.76",
    "port": 3307,
    "user": "root",
    "password": "Vlado9674+",
    "database": "medevio",
    "charset": "utf8mb4",
}

# kam uložit výstup
OUTPUT_DIR = r"U:\Dropbox\!!!Days\Downloads Z230"
DAYS_BACK = 700  # posledních X dní

# ================================
# 📘 SQL dotaz
# ================================
SQL = f"""
SELECT
    m.id AS Message_ID,
    m.request_id AS Request_ID,
    m.created_at AS Datum_vytvoření,
    m.sender_name AS Odesílatel,
    m.text AS Text_zprávy,
    m.pacient_jmeno AS Pacient_jméno,
    m.pacient_prijmeni AS Pacient_příjmení,
    m.pacient_rodnecislo AS Rodné_číslo
FROM medevio_messages m
WHERE m.created_at >= NOW() - INTERVAL {DAYS_BACK} DAY
ORDER BY m.created_at DESC;
"""

# ================================
# 🧠 MAIN
# ================================
def main():
    conn = pymysql.connect(**DB_CONFIG)
    df = pd.read_sql(SQL, conn)
    conn.close()

    today = datetime.now().strftime("%Y-%m-%d")
    output_path = f"{OUTPUT_DIR}\\Medevio_messages_report_{today}.xlsx"

    df.to_excel(output_path, index=False)

    print(f"✅ Export hotov: {output_path}")
    print(f"📄 Počet řádků: {len(df)}")

if __name__ == "__main__":
    main()
