import pathlib
import sys


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

import unified_staging_review


def test_generate_review_returns_html_for_staged_content(tmp_path, monkeypatch):
    course_id = "smoke-course-101"
    monkeypatch.setattr(unified_staging_review, "COURSES_DIR", tmp_path)

    staged_dir = tmp_path / course_id / "staging" / "pages"
    staged_dir.mkdir(parents=True)
    staged_dir.joinpath("module-1.html").write_text(
        "<h2>Smoke Review Content</h2>", encoding="utf-8"
    )

    html = unified_staging_review.generate_review(course_id)

    assert isinstance(html, str)
    assert html
    assert "<!DOCTYPE html" in html
    assert course_id in html
    assert "Smoke Review Content" in html
    assert f'data-serving-root="{tmp_path}"' in html
    assert f"Root: {tmp_path}" in html


def test_generate_review_empty_state_shows_serving_root(tmp_path, monkeypatch):
    course_id = "empty-course-101"
    monkeypatch.setattr(unified_staging_review, "COURSES_DIR", tmp_path)

    html = unified_staging_review.generate_review(course_id)

    assert f"No staged content for course {course_id}" in html
    assert f'data-serving-root="{tmp_path}"' in html
    assert "Staging server root:" in html
    assert str(tmp_path) in html


def test_generate_review_renders_staged_subheader_as_divider(tmp_path, monkeypatch):
    course_id = "subheader-course-101"
    monkeypatch.setattr(unified_staging_review, "COURSES_DIR", tmp_path)

    staged_dir = tmp_path / course_id / "staging" / "pages"
    staged_dir.mkdir(parents=True)
    staged_dir.joinpath("m1-00a-overview-section.html").write_text(
        '<h3 class="module-subheader">Overview</h3>', encoding="utf-8"
    )
    staged_dir.joinpath("m1-00a-overview-section.html.meta.json").write_text(
        '{"page_type":"subheader","subheader_text":"Overview"}',
        encoding="utf-8",
    )
    staged_dir.joinpath("m1-01-overview.html").write_text(
        "<h2>Module page</h2>", encoding="utf-8"
    )

    html = unified_staging_review.generate_review(course_id)

    assert 'class="toc-subheader"' in html
    assert 'class="staging-subheader-divider"' in html
    assert 'href="#pages-m1-00a-overview-section"' not in html
    assert 'data-id="m1-00a-overview-section"' not in html
    assert 'href="#pages-m1-01-overview"' in html


def test_generate_review_contains_no_tiptap_editor(tmp_path, monkeypatch):
    """Regression guard: the Tiptap WYSIWYG editor has been removed.
    generate_review() output must contain none of the editor tokens."""
    course_id = "no-editor-101"
    monkeypatch.setattr(unified_staging_review, "COURSES_DIR", tmp_path)

    staged_dir = tmp_path / course_id / "staging" / "pages"
    staged_dir.mkdir(parents=True)
    staged_dir.joinpath("m1-01-overview.html").write_text(
        "<h2>Overview</h2><p>Some content.</p>", encoding="utf-8"
    )

    html = unified_staging_review.generate_review(course_id)

    forbidden_tokens = [
        "@tiptap",
        "tiptap",
        "startEditing",
        "contenteditable",
        "data-cmd",
        "canvas-img-resize-handle",
    ]
    for token in forbidden_tokens:
        assert token not in html, (
            f"Editor token {token!r} found in generate_review output — "
            "the Tiptap editor must be fully removed"
        )


def test_sandbox_preview_rewrites_staged_file_tokens():
    """Banner/image tokens must become local staging-files URLs so they render
    in the unified review iframe (regression: tokens used to pass through raw)."""
    body = '<img src="asucb-staged-file://banner-m1" alt="">'
    out = unified_staging_review._sandbox_preview(body, "256162")
    assert "/courses/256162/staging-files/banner-m1" in out
    assert "asucb-staged-file://banner-m1" not in out


def test_rewrite_staged_file_tokens_rejects_malformed_keys():
    body = '<img src="asucb-staged-file://../etc/passwd">'
    out = unified_staging_review._rewrite_staged_file_tokens(body, "256162")
    # Traversal key left untouched (not rewritten into a path).
    assert "/courses/256162/staging-files/../" not in out


def test_solo_preview_button_present_for_pages(tmp_path, monkeypatch):
    course_id = "256162"
    staging = tmp_path / "courses" / course_id / "staging" / "pages"
    staging.mkdir(parents=True)
    (staging / "m1-overview.html").write_text("<h1>Overview</h1>")
    monkeypatch.setattr(unified_staging_review, "COURSES_DIR", tmp_path / "courses")
    html = unified_staging_review.generate_review(course_id)
    assert "solo-preview-btn" in html
    assert f"/courses/{course_id}/preview/pages/m1-overview" in html
