"""canvas_api.paginated_get's real Link-header traversal — mocks can't
exercise an actual multi-page Canvas response or its Link header format.
"""

import os
import sys

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

import canvas_api  # noqa: E402


def _fetch_pages(live_config, params):
    return canvas_api.paginated_get(
        f"{live_config['course_url']}/pages",
        live_config["headers"],
        params=params,
        canvas_domain=live_config["domain"],
    )


def test_paginated_get_traverses_all_pages_without_duplicates(
    live_config, page_factory, itest_prefix
):
    created_slugs = set()
    for i in range(5):
        slug, _ = page_factory(f"pagination-{i}", f"<p>ITEST-PAGINATION-{i}</p>")
        created_slugs.add(slug)

    # per_page=2 against 5 created pages forces at least 3 pages of
    # Link-header traversal (2, 2, 1) — this is the actual behavior under
    # test. search_term narrows the live response to just this run's pages
    # so the traversal stays small even in a shared sandbox course.
    results = _fetch_pages(live_config, {"per_page": 2, "search_term": itest_prefix})
    returned = {p["url"] for p in results}

    if not created_slugs <= returned:
        # Canvas's Pages index may not fuzzy-match a bracketed search_term
        # (unconfirmed live) — fall back to an unfiltered fetch, filtered
        # client-side by title, per docs/plan-live-integration-tests.md.
        results = _fetch_pages(live_config, {"per_page": 100})
        results = [
            p for p in results if str(p.get("title", "")).startswith(itest_prefix)
        ]
        returned = {p["url"] for p in results}

    returned_list = [p["url"] for p in results]
    assert len(returned_list) == len(set(returned_list)), (
        f"paginated_get returned duplicate pages: {returned_list}"
    )

    missing = created_slugs - returned
    assert not missing, (
        f"paginated_get did not return all 5 created pages; missing: {missing}"
    )
