from debputy.maintscript_snippet import (
    MaintscriptSnippetContainer,
    MaintscriptSnippet,
    SnippetResolver,
)


def test_snippet_generation() -> None:
    container = MaintscriptSnippetContainer()

    assert container.generate_snippet() is None
    assert container.generate_snippet(snippet_order="service") is None

    container.append(
        MaintscriptSnippet(
            definition_source="test/1",
            snippet=SnippetResolver.snippet_template("systemctl status\n"),
            snippet_order="service",
        )
    )
    container.append(
        MaintscriptSnippet(
            definition_source="test/2",
            snippet=SnippetResolver.snippet_template("run foo\n"),
        )
    )
    assert not container.needs_debconf()
    snippet = container.generate_snippet()
    assert snippet
    assert "run foo\n" in snippet
    assert "systemctl status\n" not in snippet
    service_snippet = container.generate_snippet(snippet_order="service")
    assert service_snippet
    assert "run foo\n" not in service_snippet
    assert "systemctl status\n" in service_snippet

    container.append(
        MaintscriptSnippet(
            definition_source="test/2",
            snippet=SnippetResolver.snippet_template("db_get foo\n"),
            uses_debconf=True,
        )
    )

    assert container.needs_debconf()
    snippet = container.generate_snippet()
    assert snippet
    assert "run foo\n" in snippet
    assert "db_get foo\n" in snippet
    assert "systemctl status\n" not in snippet
    service_snippet = container.generate_snippet(snippet_order="service")
    assert service_snippet
    assert "run foo\n" not in service_snippet
    assert "db_get foo\n" not in service_snippet
    assert "systemctl status\n" in service_snippet
    snippet_lines = snippet.splitlines(keepends=True)
    foo_idx = snippet_lines.index("run foo\n")
    db_get_idx = snippet_lines.index("db_get foo\n")
    assert foo_idx < db_get_idx

    reversed_snippet = container.generate_snippet(reverse=True)
    assert reversed_snippet
    assert "run foo\n" in reversed_snippet
    assert "db_get foo\n" in reversed_snippet
    assert "systemctl status\n" not in reversed_snippet

    reversed_snippet_lines = reversed_snippet.splitlines(keepends=True)
    reversed_foo_idx = reversed_snippet_lines.index("run foo\n")
    reversed_db_get_idx = reversed_snippet_lines.index("db_get foo\n")
    assert reversed_foo_idx > reversed_db_get_idx
