"""Backup recipes as code (Wave-2 P0.1) — the drift gates.

The three nightly backup scripts in ``backups/`` are the canonical recipes; the
``examples/*-backup-cloud-init-fragment.yml`` fragments embed them for rebuilds.
These tests byte-pin fragment ↔ script (the lock-program method: the
consolidation ships WITH the gate that keeps it converged), and pin the
survival-critical properties: every script ends by posting a heartbeat, prunes
its retention window, and commits no secret values (heartbeat URL/token are
FILE PATHS, pushed post-provision).
"""

from __future__ import annotations

from pathlib import Path

import pytest

yaml = pytest.importorskip("yaml")  # PyYAML rides in via mgf-cloud[infomaniak] (CI installs it)

_REPO = Path(__file__).resolve().parents[4]
_BACKUPS = _REPO / "backups"
_EXAMPLES = _REPO / "examples"

_JOBS = [
    ("devpi-export-nightly.sh", "devpi-backup-cloud-init-fragment.yml", "mgf-backup-devpi", "7"),
    ("pg-dump-nightly.sh", "woodpecker-pg-backup-cloud-init-fragment.yml", "mgf-backup-pg", "14"),
    ("oo-snapshot-nightly.sh", "openobserve-backup-cloud-init-fragment.yml", "mgf-backup-oo", "7"),
]


@pytest.mark.parametrize(("script", "fragment", "cron", "_keep"), _JOBS)
def test_fragment_embeds_the_canonical_script_byte_identical(
    script: str, fragment: str, cron: str, _keep: str
) -> None:
    doc = yaml.safe_load((_EXAMPLES / fragment).read_text(encoding="utf-8"))
    files = {w["path"]: w for w in doc["write_files"]}
    embedded = files[f"/usr/local/bin/{script}"]
    assert embedded["content"] == (_BACKUPS / script).read_text(encoding="utf-8"), (
        f"{fragment} drifted from backups/{script} — edit the script, then re-embed"
    )
    assert embedded["permissions"] == "0750"
    # the cron.d entry installs the same path the fragment writes
    cron_entry = files[f"/etc/cron.d/{cron}"]
    assert f"/usr/local/bin/{script}" in cron_entry["content"]
    assert "root" in cron_entry["content"]  # /etc/cron.d needs the user field


@pytest.mark.parametrize(("script", "_fragment", "_cron", "keep"), _JOBS)
def test_script_survival_properties(script: str, _fragment: str, _cron: str, keep: str) -> None:
    text = (_BACKUPS / script).read_text(encoding="utf-8")
    assert text.startswith("#!/usr/bin/env bash")
    assert "set -euo pipefail" in text
    # ends by POSTing a heartbeat (dead-man's-switch: posted only on success)
    assert "post_heartbeat" in text
    assert text.rstrip().splitlines()[-1].startswith("post_heartbeat ")
    # retention prune, parameterized
    assert f'KEEP_DAYS="${{KEEP_DAYS:-{keep}}}"' in text
    assert "-mtime" in text and "-delete" in text
    # heartbeat endpoint/token are FILE PATHS under /etc/mgf — never inline values
    assert "/etc/mgf/backup-heartbeat.url" in text
    assert "/etc/mgf/backup-heartbeat.token" in text
    for forbidden in ("Bearer ", "Basic ", "https://195."):
        assert forbidden not in text, f"{script} must not carry credential/endpoint values"


def test_devpi_export_always_restarts_the_server() -> None:
    text = (_BACKUPS / "devpi-export-nightly.sh").read_text(encoding="utf-8")
    assert "systemctl stop devpi" in text
    # the trap guarantees restart even when the export fails mid-way
    assert "trap 'systemctl start devpi" in text


def test_ops_scripts_are_co_located() -> None:
    # Self-heal co-location (P0.4): this repo is the canonical home; the mgf-fed
    # copies carry DEPRECATED headers.
    assert (_REPO / "ops" / "self-heal.sh").is_file()
    assert (_REPO / "ops" / "agent-reconciler.py").is_file()
    assert "canonical" in (_REPO / "ops" / "self-heal.sh").read_text(encoding="utf-8").lower()
