"""Backups: one zip with a consistent copy of the database (SQLite online backup) and the uploaded files.

Made on demand from Settings → Backups, or daily with `python manage.py daily` (cron / Task Scheduler). The newest
KEEP backups are kept in instance/backups; copy them off the server (another disk or cloud storage) as well.
Restore: stop the app, unzip, put vertex.db and uploads/ back in the instance folder, start the app.
"""
import os
import sqlite3
import tempfile
import zipfile
from datetime import datetime

from flask import current_app

KEEP = 30


def instance_dir():
    return os.path.dirname(current_app.config["DATABASE"])


def folder():
    path = os.environ.get("VERTEX_BACKUP_DIR") or os.path.join(instance_dir(), "backups")
    os.makedirs(path, exist_ok=True)
    return path


def make_backup(label="manual"):
    """Returns the path of the new zip."""
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    name = f"vertex-{stamp}-{label}.zip"
    dest = os.path.join(folder(), name)
    with tempfile.TemporaryDirectory() as tmp:
        copy = os.path.join(tmp, "vertex.db")
        src = sqlite3.connect(current_app.config["DATABASE"])
        dst = sqlite3.connect(copy)
        with dst:
            src.backup(dst)
        src.close()
        dst.close()
        with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
            z.write(copy, "vertex.db")
            up = os.path.join(instance_dir(), "uploads")
            for root, _, files in os.walk(up):
                for f in files:
                    full = os.path.join(root, f)
                    z.write(full, os.path.join("uploads", os.path.relpath(full, up)))
            lic = os.path.join(instance_dir(), "license.json")
            if os.path.exists(lic):
                z.write(lic, "license.json")
    prune()
    return dest


def listing():
    out = []
    for f in sorted(os.listdir(folder()), reverse=True):
        if f.startswith("vertex-") and f.endswith(".zip"):
            p = os.path.join(folder(), f)
            out.append({"name": f, "size": os.path.getsize(p),
                        "at": datetime.fromtimestamp(os.path.getmtime(p)).strftime("%Y-%m-%d %H:%M")})
    return out


def prune(keep=KEEP):
    for b in listing()[keep:]:
        try:
            os.remove(os.path.join(folder(), b["name"]))
        except OSError:
            pass


def path_of(name):
    name = os.path.basename(name)
    p = os.path.join(folder(), name)
    if not (name.startswith("vertex-") and name.endswith(".zip") and os.path.exists(p)):
        return None
    return p
