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

"""
Simplified Medicus Firebird database restore
✅ Works locally with Firebird service running
✅ Handles spaces in paths
✅ Restores newest .fbk backup from restore folder
"""

import subprocess
from pathlib import Path

# =========================================
# 🔧 CONFIGURATION
# =========================================
FIREBIRD_GBAK = Path(r"C:\Program Files\Firebird\Firebird_2_5_CGM\bin\gbak.exe")
RESTORE_DIR = Path(r"Z:\Medicus 3\restore")
TARGET_DB = Path(r"Z:\Medicus 3\data\MEDICUS.FDB")
USER = "SYSDBA"
PASSWORD = "masterkey"

# =========================================
# 🔍 Find newest .fbk file
# =========================================
fbk_files = list(RESTORE_DIR.glob("*.fbk"))
if not fbk_files:
    raise SystemExit(f"❌ No .fbk files found in {RESTORE_DIR}")

latest_fbk = max(fbk_files, key=lambda f: f.stat().st_mtime)
print(f"🕒 Latest FBK: {latest_fbk.name}")

# =========================================
# 🧩 Build gbak command (direct restore)
# =========================================
cmd = f'"{FIREBIRD_GBAK}" -rep "{latest_fbk}" "{TARGET_DB}" -user {USER} -pas {PASSWORD}'
print("\n🧩 Running restore command:")
print(cmd)

# =========================================
# ▶️ Execute restore
# =========================================
result = subprocess.run(cmd, shell=True, text=True, capture_output=True)

if result.returncode == 0:
    print("✅ Medicus database successfully restored!")
else:
    print("❌ Restore failed:")
    print(result.stderr.strip() or result.stdout.strip())
