"""push_remediated_file.py's Canvas delivery flow — backup -> upload overwrite
-> verify -> clear staging -> backlog close — exercised against a real Canvas
file instead of mocks (plan §4, AC14).

Creates a throwaway file, "remediates" it with a trivial replacement (this
test does not exercise the PDF/DOCX/PPTX engines — only the Canvas delivery
path), verifies the replace took, then deletes the throwaway via the new
canvas_api.delete_file(). Never touches a standing sandbox fixture.

Like every file under tests/integration/, this is skipped unless
ASUCB_LIVE_TEST=1 (see conftest.py's pytest_collection_modifyitems) — it is
NOT run as part of this change: the sandbox token is expired as of this PR
(see docs/plan-file-remediation-skill.md §4). It is structured and ready to
run the next time a valid token is available.
"""

import os
import sys

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

import canvas_api  # noqa: E402
import push_remediated_file  # noqa: E402


def test_replace_throwaway_file_backup_upload_verify(live_config, run_id, tmp_path):
    course_id = live_config["course_id"]

    folder_id = canvas_api.get_or_create_folder(
        live_config, "course files", f"itest-{run_id}"
    )
    assert folder_id, "get_or_create_folder did not return a folder id"

    original = tmp_path / "original.txt"
    original.write_text(f"[ITEST-{run_id}] original throwaway content", encoding="utf-8")

    file_id = canvas_api.upload_file(
        live_config, str(original), folder_id, content_type="text/plain",
        filename=f"itest-{run_id}-throwaway.txt",
    )
    assert file_id, "upload_file did not return a file id for the throwaway fixture"

    staging_dir = os.path.join(
        canvas_api.get_plugin_root(), "courses", course_id, "staging", "files")
    os.makedirs(staging_dir, exist_ok=True)
    staged_path = os.path.join(staging_dir, f"itest-{run_id}-replacement.txt")
    replacement_text = f"[ITEST-{run_id}] replacement content is longer than the original"
    with open(staged_path, "w", encoding="utf-8") as f:
        f.write(replacement_text)
    expected_size = os.path.getsize(staged_path)

    result = None
    try:
        result = push_remediated_file.push_remediated_file(
            course_id, file_id, staged_path, "push"
        )
        assert result["ok"], f"push_remediated_file failed: {result}"
        assert not os.path.exists(staged_path), "staged file should be cleared on success"
        assert os.path.exists(result["backup_path"]), "pre-push backup should exist"

        verify_id = int(result["verified_file_id"])
        live = canvas_api.get_file(live_config, verify_id)
        assert live is not None, f"replaced file {verify_id} not found via get_file"
        assert live["size"] == expected_size
    finally:
        if os.path.exists(staged_path):
            os.remove(staged_path)
        if result and result.get("backup_path"):
            for candidate in (result["backup_path"], result["backup_path"] + ".meta.json"):
                if os.path.exists(candidate):
                    os.remove(candidate)
        cleanup_id = int(result["verified_file_id"]) if result and result.get("ok") else int(file_id)
        try:
            canvas_api.delete_file(live_config, cleanup_id, confirm=True)
        except Exception as exc:  # noqa: BLE001 — best-effort teardown
            print(f"  cleanup: failed to delete throwaway file {cleanup_id}: {exc}")
