"""Tests for the --scorm opt-in path in deploy_interactives.py --html-file mode.

- --scorm packages the HTML as a SCORM 1.2 .zip (bridge + manifest) and prints
  upload instructions.
- --scorm does NOT require --confirm-verb (producing a local zip is not a Canvas
  write) and makes no Canvas API calls.
- Default (no --scorm) path is unaffected.
"""

import os
import sys
import zipfile
import pathlib
import tempfile
from unittest import mock

SCRIPTS_DIR = pathlib.Path(__file__).resolve().parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS_DIR))

import deploy_interactives as di  # noqa: E402
import package_scorm as ps  # noqa: E402


def _make_html_file(content="<html><head></head><body><h1>x</h1></body></html>"):
    tmp = tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode="w")
    tmp.write(content)
    tmp.close()
    return tmp.name


def _run(argv):
    with mock.patch("sys.argv", ["deploy_interactives"] + argv):
        try:
            di.main()
            return 0
        except SystemExit as exc:
            return exc.code


def test_scorm_produces_zip_without_confirm_verb(tmp_path, capsys):
    html = _make_html_file()
    out = str(tmp_path / "x-SCORM.zip")
    # No --confirm-verb, no Canvas mock needed: --scorm must not call Canvas.
    rc = _run(["--html-file", html, "--title", "T", "--scorm", "--scorm-output", out])
    assert rc in (0, None)
    assert os.path.isfile(out)
    with zipfile.ZipFile(out) as zf:
        names = set(zf.namelist())
        assert names == {"imsmanifest.xml", "index.html"}
        body = zf.read("index.html").decode()
    assert ps.BRIDGE_SENTINEL in body
    captured = capsys.readouterr()
    assert "SCORM package ready" in captured.out
    os.unlink(html)


def test_scorm_scored_mastery_in_manifest(tmp_path):
    html = _make_html_file()
    out = str(tmp_path / "scored-SCORM.zip")
    rc = _run(["--html-file", html, "--title", "Sim", "--scorm",
               "--scorm-mode", "scored", "--scorm-mastery", "70", "--scorm-output", out])
    assert rc in (0, None)
    with zipfile.ZipFile(out) as zf:
        manifest = zf.read("imsmanifest.xml").decode()
    assert "<adlcp:masteryscore>70</adlcp:masteryscore>" in manifest
    os.unlink(html)


def test_scorm_makes_no_canvas_calls(tmp_path):
    """--scorm must not touch the Canvas API (would raise if it tried)."""
    html = _make_html_file()
    out = str(tmp_path / "y-SCORM.zip")
    with mock.patch.object(di, "get_config", side_effect=AssertionError("Canvas call!")):
        rc = _run(["--html-file", html, "--title", "T", "--scorm", "--scorm-output", out])
    assert rc in (0, None)
    assert os.path.isfile(out)
    os.unlink(html)
