import subprocess
from pathlib import Path
from datetime import datetime
import traceback
import sys

from EmailMessagingGraph import send_mail

# =========================
# CONFIG – TEST PC
# =========================

GBAK = r"C:\Program Files\Firebird\Firebird_2_5_CGM\bin\gbak.exe"
DB = r"localhost/3050:Z:\Medicus 3\data\MEDICUS.FDB"
BACKUP_DIR = Path(r"D:\medicusbackup")

FB_USER = "SYSDBA"
FB_PASS = "masterkey"

MAIL_TO = "vladimir.buzalka@buzalka.cz"

# =========================
# MAIN
# =========================

def main():
    BACKUP_DIR.mkdir(parents=True, exist_ok=True)

    now = datetime.now()
    ts = now.strftime("%Y-%m-%d_%H-%M-%S")

    fbk = BACKUP_DIR / f"MEDICUS_{ts}.fbk"
    log = BACKUP_DIR / f"MEDICUS_{ts}.log"

    cmd = [
        GBAK,
        "-b",
        "-user", FB_USER,
        "-pas", FB_PASS,
        DB,
        str(fbk),
        "-v",
    ]

    try:
        with open(log, "w", encoding="utf-8") as f:
            subprocess.run(
                cmd,
                stdout=f,
                stderr=subprocess.STDOUT,
                check=True,
            )

        send_mail(
            MAIL_TO,
            "✅ MEDICUS – záloha OK (test PC)",
            f"""Záloha MEDICUS proběhla úspěšně.

Čas: {now}
Soubor: {fbk}
Log: {log}
""",
        )

    except Exception:
        err = traceback.format_exc()

        send_mail(
            MAIL_TO,
            "❌ MEDICUS – CHYBA ZÁLOHY (test PC)",
            f"""Při záloze MEDICUS došlo k chybě.

Čas: {now}

Chyba:
{err}

Log:
{log}
""",
        )
        raise


if __name__ == "__main__":
    main()
