#!/usr/bin/env python3
"""
Daily backup of all state files. Keeps a rolling 14-day window.
Files backed up:
  - buckets.json (partner/teacher/CRM/archive assignments)
  - bump_overrides.json (manual bump number overrides)
  - skip_list.txt (handles to never DM)
  - activity_log.json (DM history)
  - config.json (if exists)

Run daily via launchagent. Restore from /backups/{date}/<file>.
"""
import shutil
from datetime import datetime, timedelta
from pathlib import Path

BASE = Path(__file__).parent
BACKUP_ROOT = BASE / "backups"
KEEP_DAYS = 14

FILES_TO_BACKUP = [
    "buckets.json",
    "bump_overrides.json",
    "skip_list.txt",
    "activity_log.json",
    "config.json",
]


def main():
    today = datetime.now().strftime("%Y-%m-%d")
    backup_dir = BACKUP_ROOT / today
    backup_dir.mkdir(parents=True, exist_ok=True)

    backed_up = []
    for fname in FILES_TO_BACKUP:
        src = BASE / fname
        if not src.exists():
            continue
        dst = backup_dir / fname
        try:
            shutil.copy2(src, dst)
            backed_up.append(fname)
        except Exception as e:
            print(f"[backup] failed {fname}: {e}")

    print(f"[backup {today}] saved {len(backed_up)} files: {', '.join(backed_up)}")

    # Cleanup old backups (older than KEEP_DAYS)
    if BACKUP_ROOT.exists():
        cutoff = datetime.now() - timedelta(days=KEEP_DAYS)
        removed = 0
        for d in BACKUP_ROOT.iterdir():
            if not d.is_dir():
                continue
            try:
                d_date = datetime.strptime(d.name, "%Y-%m-%d")
                if d_date < cutoff:
                    shutil.rmtree(d)
                    removed += 1
            except ValueError:
                continue
        if removed:
            print(f"[backup] cleaned {removed} old backup dirs (>{KEEP_DAYS} days)")


if __name__ == "__main__":
    main()
