"""
soul.db rolling backup script
- Uses sqlite3.backup() API (atomic backup, never copies mid-write state)
- Timestamp precision down to microseconds to avoid same-second collisions
- Retains the latest MAX_COPIES copies, deletes the oldest beyond that
- Backup directory: soul-mcp/backups/
"""

import sqlite3
from datetime import datetime
from pathlib import Path

MAX_COPIES = 3
SOUL_DIR   = Path(__file__).parent
DB_FILE    = SOUL_DIR / "soul.db"
BACKUP_DIR = SOUL_DIR / "backups"


def run():
    if not DB_FILE.exists():
        print("[backup] soul.db does not exist, skipping")
        return

    BACKUP_DIR.mkdir(exist_ok=True)

    # Microsecond-precision timestamp to avoid same-second concurrent collisions
    ts   = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
    dest = BACKUP_DIR / f"soul_{ts}.db"

    # sqlite3 atomic backup: waits for all transactions to complete before copying
    src  = sqlite3.connect(str(DB_FILE))
    dst  = sqlite3.connect(str(dest))
    src.backup(dst)
    dst.close()
    src.close()

    # Keep only the latest MAX_COPIES, delete the rest
    copies = sorted(BACKUP_DIR.glob("soul_*.db"), key=lambda p: p.stat().st_mtime)
    for old in copies[:-MAX_COPIES]:
        old.unlink()
        print(f"[backup] Deleted old copy: {old.name}")

    kept = sorted(BACKUP_DIR.glob("soul_*.db"), key=lambda p: p.stat().st_mtime)
    print(f"[backup] Backed up -> {dest.name}  ({len(kept)} copies retained)")


if __name__ == "__main__":
    run()
