#!/usr/bin/env python3

import os
import re
import subprocess
from datetime import datetime
from pathlib import Path
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment

BACKUP_LABELS = ["MARTES-JUEVES", "Lun-Mier", "Viernes-1-3-5", "VIE-2-4"]
MOUNT_BASE = "/mnt/backup-auto"
EXCEL_PATH = "/home/informatica/Documentos/backups_tamaños.xlsx"
DATE_PATTERN = re.compile(r'^[DSM]_\d{4}-\d{2}-\d{2}$')


def get_mounted_backup_disk():
    """Returns (label, mount_point) of the first connected backup disk, or None."""
    for label in BACKUP_LABELS:
        # Check if already mounted
        result = subprocess.run(
            ["findmnt", "-n", "-o", "TARGET", "-S", "LABEL=" + label],
            capture_output=True, text=True
        )
        mount_point = result.stdout.strip()
        if mount_point and os.path.isdir(mount_point):
            return label, mount_point

        # Try mounting it
        device_result = subprocess.run(
            ["blkid", "-L", label], capture_output=True, text=True
        )
        device = device_result.stdout.strip()
        if device:
            mount_point = os.path.join(MOUNT_BASE, label)
            os.makedirs(mount_point, exist_ok=True)
            r = subprocess.run(["mount", device, mount_point], capture_output=True)
            if r.returncode == 0:
                return label, mount_point

    return None, None


def get_most_recent_backup(mount_point):
    """Returns (folder_name, size_str) of the most recent dated backup folder."""
    try:
        folders = [f for f in os.listdir(mount_point) if DATE_PATTERN.match(f)]
    except PermissionError:
        return None, None

    if not folders:
        return None, None

    folders.sort(reverse=True)
    newest = folders[0]
    folder_path = os.path.join(mount_point, newest)

    # Calculate size
    result = subprocess.run(
        ["du", "-sh", folder_path], capture_output=True, text=True
    )
    size = result.stdout.split()[0] if result.stdout else "N/D"
    return newest, size


def update_excel(fecha, disco, backup_name, backup_size):
    path = Path(EXCEL_PATH)
    path.parent.mkdir(parents=True, exist_ok=True)

    if path.exists():
        wb = openpyxl.load_workbook(path)
        ws = wb.active
    else:
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "Backups"

        # Header
        headers = ["Fecha", "Disco", "Backup más reciente", "Tamaño"]
        header_fill = PatternFill("solid", fgColor="1F4E79")
        header_font = Font(bold=True, color="FFFFFF")
        for col, h in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=h)
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = Alignment(horizontal="center")

        ws.column_dimensions["A"].width = 14
        ws.column_dimensions["B"].width = 18
        ws.column_dimensions["C"].width = 24
        ws.column_dimensions["D"].width = 12

    # Append data row
    row = ws.max_row + 1
    ws.cell(row=row, column=1, value=fecha)
    ws.cell(row=row, column=2, value=disco if disco else "Ninguno conectado")
    ws.cell(row=row, column=3, value=backup_name if backup_name else "N/D")
    ws.cell(row=row, column=4, value=backup_size if backup_size else "N/D")

    # Alternate row color
    if row % 2 == 0:
        fill = PatternFill("solid", fgColor="D6E4F0")
        for col in range(1, 5):
            ws.cell(row=row, column=col).fill = fill

    wb.save(path)
    print(f"[{fecha}] Planilla actualizada: disco={disco}, backup={backup_name}, tamaño={backup_size}")


if __name__ == "__main__":
    fecha = datetime.now().strftime("%Y-%m-%d")
    label, mount_point = get_mounted_backup_disk()

    mounted_here = False
    backup_name = None
    backup_size = None

    if label and mount_point:
        backup_name, backup_size = get_most_recent_backup(mount_point)
        # Unmount only if we mounted it
        result = subprocess.run(
            ["findmnt", "-n", "-o", "TARGET", "-S", "LABEL=" + label],
            capture_output=True, text=True
        )
        existing_mount = result.stdout.strip()
        if existing_mount == os.path.join(MOUNT_BASE, label):
            subprocess.run(["umount", mount_point])

    update_excel(fecha, label, backup_name, backup_size)
