"""``python -m app.backup`` — one pull, exit code telling the truth.

Run by the operating system's scheduler on the off-site machine, not by the
intake daemon (see the package docstring for why). Configuration is its own
set of variables: the puller holds a dedicated ``backups.read`` identity, and
sharing the daemon's names would invite sharing the daemon's credential.

    TAXPILOT_CMS_URL              the installation to mirror
    TAXPILOT_BACKUP_AGENT_KEY     the dedicated agent's key
    TAXPILOT_BACKUP_AGENT_SECRET  its secret
    TAXPILOT_BACKUP_DEST          where the mirror lives on this machine
    TAXPILOT_BACKUP_KEEP          copies kept per artefact family (default 7)
"""

from __future__ import annotations

import logging
import os
import sys
from pathlib import Path

from app.backup.puller import BackupPuller, PullError


def main(env: dict[str, str] | None = None) -> int:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

    env = env if env is not None else dict(os.environ)

    missing = [
        name
        for name in ("TAXPILOT_CMS_URL", "TAXPILOT_BACKUP_AGENT_KEY",
                     "TAXPILOT_BACKUP_AGENT_SECRET", "TAXPILOT_BACKUP_DEST")
        if not env.get(name)
    ]

    if missing:
        print("The backup puller is not configured. Missing: " + ", ".join(missing))

        return 2

    puller = BackupPuller(
        cms_base_url=env["TAXPILOT_CMS_URL"],
        api_key=env["TAXPILOT_BACKUP_AGENT_KEY"],
        api_secret=env["TAXPILOT_BACKUP_AGENT_SECRET"],
        destination=Path(env["TAXPILOT_BACKUP_DEST"]),
        keep_per_family=int(env.get("TAXPILOT_BACKUP_KEEP", "7")),
    )

    try:
        result = puller.pull()
    except PullError as failure:
        print(f"PULL FAILED: {failure}")

        return 1

    print(
        f"Pulled {len(result.fetched)}, "
        f"already held {len(result.already_present)}, "
        f"pruned {len(result.pruned)}."
    )

    return 0


if __name__ == "__main__":
    sys.exit(main())
