"""Tests for Canvas syllabus and module overview scrapers."""

import os
import sys
from unittest.mock import MagicMock, patch

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

import canvas_api


def _mock_config():
    return {
        "token": "fake",
        "domain": "canvas.test.edu",
        "course_id": "99999",
        "base_url": "https://canvas.test.edu/api/v1",
        "course_url": "https://canvas.test.edu/api/v1/courses/99999",
        "headers": {"Authorization": "Bearer fake"},
    }


def _response(payload, status=200, links=""):
    response = MagicMock()
    response.status_code = status
    response.headers = {"Link": links}
    response.json.return_value = payload
    response.raise_for_status.return_value = None
    return response


@patch("canvas_api._request_with_retry")
def test_get_syllabus_fetches_body_url_and_updated_at(mock_request):
    mock_request.return_value = _response({
        "syllabus_body": "<h2>Course Objectives</h2>",
        "html_url": "https://canvas.test.edu/courses/99999",
        "updated_at": "2026-05-01T12:00:00Z",
    })

    result = canvas_api.get_syllabus(_mock_config())

    assert result == {
        "html": "<h2>Course Objectives</h2>",
        "page_url": "https://canvas.test.edu/courses/99999",
        "updated_at": "2026-05-01T12:00:00Z",
    }
    assert mock_request.call_args.kwargs["params"] == {"include[]": "syllabus_body"}


@patch("canvas_api._request_with_retry")
def test_get_module_overview_page_prefers_overview_page(mock_request):
    mock_request.side_effect = [
        _response([
            {"id": 1, "type": "Page", "title": "Lesson", "page_url": "m1-lesson"},
            {"id": 2, "type": "Page", "title": "Module 1 Overview", "page_url": "m1-overview"},
        ]),
        _response({
            "body": "<h2>Module objectives</h2>",
            "html_url": "https://canvas.test.edu/courses/99999/pages/m1-overview",
            "url": "m1-overview",
        }),
    ]

    result = canvas_api.get_module_overview_page(_mock_config(), 123)

    assert result == {
        "html": "<h2>Module objectives</h2>",
        "page_url": "https://canvas.test.edu/courses/99999/pages/m1-overview",
        "page_slug": "m1-overview",
        "module_id": 123,
    }
    assert "/modules/123/items" in mock_request.call_args_list[0].args[1]
    assert mock_request.call_args_list[1].args[1].endswith("/pages/m1-overview")


@patch("canvas_api._request_with_retry")
def test_get_module_overview_page_returns_none_without_page_item(mock_request):
    mock_request.return_value = _response([
        {"id": 1, "type": "SubHeader", "title": "Start Here"},
        {"id": 2, "type": "Quiz", "title": "Knowledge Check"},
    ])

    assert canvas_api.get_module_overview_page(_mock_config(), 123) is None
