#!/usr/bin/env python3
"""
Backup automatico Talent Risk — scorecard, guida, ticket.
Eseguito ogni ora via cron.
Copia i file in ~/.hermes/backups/talent-risk/YYYY-MM-DD_HH-MM/
E mantiene sempre un link "latest" all'ultimo backup.
"""
import shutil, os, sys
from datetime import datetime

HOME = os.path.expanduser('~/.hermes')
BACKUP_DIR = os.path.join(HOME, 'backups', 'talent-risk')
LATEST_LINK = os.path.join(BACKUP_DIR, 'latest')

FILES = {
    "scorecard": "/home/oem/Scorecard_TalentRisk_Reale_Cippa.xlsx",
    "guida":     "/home/oem/Guida_Dummies_Scorecard_Cippa.docx",
    "ticket":    os.path.join(HOME, 'tickets', 'talent_risk_2026_06_14.json'),
}

timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M')
dest_dir = os.path.join(BACKUP_DIR, timestamp)

os.makedirs(dest_dir, exist_ok=True)

copied = 0
errors = []
for name, src in FILES.items():
    if os.path.exists(src):
        dst = os.path.join(dest_dir, os.path.basename(src))
        shutil.copy2(src, dst)
        copied += 1
    else:
        errors.append(f"{name}: {src} non trovato")

# Aggiorna link latest
if os.path.islink(LATEST_LINK) or os.path.exists(LATEST_LINK):
    os.remove(LATEST_LINK)
os.symlink(timestamp, LATEST_LINK)

# Pulisci backup più vecchi di 30 giorni (tiene 720 copie orarie)
import time
now = time.time()
for d in os.listdir(BACKUP_DIR):
    dp = os.path.join(BACKUP_DIR, d)
    if d == 'latest' or not os.path.isdir(dp):
        continue
    try:
        ft = datetime.strptime(d, '%Y-%m-%d_%H-%M').timestamp()
        if now - ft > 30 * 86400:
            shutil.rmtree(dp)
            print(f"[PULITO] backup vecchio: {d}")
    except:
        pass

print(f"[OK] Backup {timestamp}: {copied}/{len(FILES)} file copiati in {dest_dir}")
for e in errors:
    print(f"[WARN] {e}")
sys.exit(0 if copied > 0 else 1)
