"""canvas_api.delete_page's confirm=True gate (§Write Safety Guard, CLAUDE.md),
exercised against a real page instead of a mock.
"""

import os
import sys

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "scripts"))

import backup_manager  # noqa: E402
import canvas_api  # noqa: E402


def test_delete_without_confirm_raises_and_page_survives(live_config, page_factory):
    slug, _ = page_factory("delete-gate-no-confirm", "<p>ITEST-DELETE-GATE</p>")

    with pytest.raises(PermissionError):
        canvas_api.delete_page(live_config, slug)

    page = canvas_api.get_page(live_config, slug)
    assert page is not None, "Page should still be live after a refused delete"


def test_delete_with_confirm_removes_page_and_backs_up(live_config, page_factory, wait_for):
    slug, _ = page_factory("delete-gate-confirm", "<p>ITEST-DELETE-GATE-CONFIRM</p>")

    ok = canvas_api.delete_page(live_config, slug, confirm=True)
    assert ok is True

    def _gone():
        return canvas_api.get_page(live_config, slug) is None

    assert wait_for(_gone) is True, (
        "Expected get_page to return None (404) after a confirmed delete"
    )

    backups = backup_manager.list_backups(live_config["course_id"], "pages", slug)
    assert backups, "Expected a pre-delete backup to exist locally"
