"""
restore_backup.py — the database copies stored on MinIO (services/backup_service.py). Run from backend/.

    venv/bin/python scripts/restore_backup.py list                 the copies in the bucket, newest first
    venv/bin/python scripts/restore_backup.py check [NAME]         loads one (default: the newest) into a THROWAWAY database
    venv/bin/python scripts/restore_backup.py fetch NAME [FILE]    downloads and decrypts it to a .sql.gz file

This script never writes to the live database, on purpose: replacing it is a decision for a person, with the app stopped:

    gunzip -c meeconic_YYYYMMDD_HHMM.sql.gz | mysql -u USER -p meeconic
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from services import backup_service as b  # noqa: E402


def main() -> int:
    args = sys.argv[1:]
    if not args or args[0] not in ("list", "check", "fetch"):
        print(__doc__)
        return 2
    if not b.offsite_configured():
        print("Missing BACKUP_ENCRYPTION_KEY or S3_* in .env.")
        return 1
    if args[0] == "list":
        for x in b.list_offsite():
            print(f"{x['name']}  {x['size'] / 1024:.0f} KB  {x['modified']}")
        return 0
    if args[0] == "check":
        copies = b.list_offsite()
        name = args[1] if len(args) > 1 else (copies[0]["name"] if copies else None)
        if not name:
            print("No copy in the bucket.")
            return 1
        r = b.restore_check(b.fetch_offsite(name))
        print(f"OK {name}: restored {r['tables']} tables, {r['rows']} rows, counts match, throwaway database dropped.")
        return 0
    if len(args) < 2:
        print(__doc__)
        return 2
    out = Path(args[2]) if len(args) > 2 else Path(args[1].removesuffix(".enc"))
    if out.exists():
        print(f"{out} already exists: nothing written.")
        return 1
    out.write_bytes(b.fetch_offsite(args[1]))
    print(f"Written: {out} (holds personal data: delete it when done)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
