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

"""
Find the latest Medicus backup (.fbk or .zip) in the given folder.
If the newest backup is a ZIP, extract the .fbk into Z:\Medicus 3\restore.
Before extraction, the restore folder is fully cleared.
Prints the full path to the resulting .fbk file (for batch usage).
"""

import re
import zipfile
import shutil
from pathlib import Path
from datetime import datetime

# ========================================
# 🔧 CONFIGURATION
# ========================================
BACKUP_DIR = Path(r"G:\OnedriveOrdinace\OneDrive\MedicusBackup")  # ✅ your real backup location
RESTORE_DIR = Path(r"Z:\\Medicus 3\\restore")                        # destination folder for .fbk
RESTORE_DIR.mkdir(parents=True, exist_ok=True)

# ========================================
# 🧹 1) Clean restore folder
# ========================================
print(f"🧹 Cleaning folder: {RESTORE_DIR}")
for item in RESTORE_DIR.iterdir():
    try:
        if item.is_file() or item.is_symlink():
            item.unlink()
        elif item.is_dir():
            shutil.rmtree(item)
    except Exception as e:
        print(f"⚠️ Cannot delete {item}: {e}")

# ========================================
# 🔍 2) Find newest backup file
# ========================================
pattern = re.compile(r"Medicus_(\d{6})_(\d{4})\.(fbk|zip)$", re.IGNORECASE)
candidates = []

for f in BACKUP_DIR.iterdir():
    m = pattern.match(f.name)
    if m:
        yymmdd, hhmm, ext = m.groups()
        ts = datetime.strptime("20" + yymmdd + hhmm, "%Y%m%d%H%M")
        candidates.append((ts, f))

if not candidates:
    raise SystemExit("❌ No Medicus backup files found in folder!")

candidates.sort(key=lambda x: x[0], reverse=True)
latest_time, latest_file = candidates[0]

print(f"🕒 Latest backup: {latest_file.name} ({latest_time})")

# ========================================
# 📦 3) Extract or use directly
# ========================================
if latest_file.suffix.lower() == ".zip":
    with zipfile.ZipFile(latest_file, "r") as zf:
        fbk_files = [n for n in zf.namelist() if n.lower().endswith(".fbk")]
        if not fbk_files:
            raise SystemExit("❌ ZIP file does not contain any .fbk!")
        fbk_name = Path(fbk_files[0]).name
        out_path = RESTORE_DIR / fbk_name
        print(f"📂 Extracting {fbk_name} → {out_path}")
        zf.extract(fbk_files[0], RESTORE_DIR)
        final_fbk = out_path
else:
    out_path = RESTORE_DIR / latest_file.name
    print(f"📋 Copying {latest_file} → {out_path}")
    shutil.copy2(latest_file, out_path)
    final_fbk = out_path

# ========================================
# ✅ 4) Output final .fbk path for the batch file
# ========================================
print(final_fbk)
