# retoor <retoor@molodetz.nl>

from devplacepy.services.containers import forward

PREFIX = "/projects/demo/containers/instances/abc/code"


def test_the_root_document_is_the_empty_or_slash_path():
    assert forward.is_root_document("") is True
    assert forward.is_root_document("/") is True
    assert forward.is_root_document("//") is True


def test_a_nested_path_is_never_the_root_document():
    for path in (
        "index.html",
        "login",
        "stable-abc/static/out/vs/workbench/contrib/webview/browser/pre/index.html",
        "nested/page.html",
        "/nested/",
    ):
        assert forward.is_root_document(path) is False, path


def test_inject_base_adds_a_base_after_head():
    body = b"<!doctype html><html><head><meta charset=utf-8></head><body>x</body></html>"
    injected = forward.inject_base(body, PREFIX)
    assert injected.startswith(b"<!doctype html><html><head>" + f'<base href="{PREFIX}/">'.encode())


def test_inject_base_leaves_an_existing_base_alone():
    body = b'<html><head><base href="./"></head><body></body></html>'
    assert forward.inject_base(body, PREFIX) == body


def test_inject_base_prepends_when_there_is_no_head_or_html():
    body = b"<p>fragment</p>"
    assert forward.inject_base(body, PREFIX) == f'<base href="{PREFIX}/">'.encode() + body


def test_rewrite_location_prefixes_only_absolute_paths():
    assert forward.rewrite_location("/login", PREFIX) == f"{PREFIX}/login"
    assert forward.rewrite_location("./login", PREFIX) == "./login"
    assert forward.rewrite_location("//cdn.example/x", PREFIX) == "//cdn.example/x"
    assert forward.rewrite_location("/login", "") == "/login"
