from debputy.maintscript_snippet import (
    MaintscriptSnippetContainer,
    UnboundMaintscriptSnippet,
    SnippetResolver,
    SnippetAnchor,
)


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

    assert (
        container.generate_snippet(
            snippet_anchor=SnippetAnchor._BETWEEN_CONFIGURATION_MANAGEMENT_AND_SERVICE,
        )
        is None
    )
    assert container.generate_snippet(snippet_anchor=SnippetAnchor.SERVICE) is None

    container.append(
        UnboundMaintscriptSnippet(
            definition_source="test/1",
            snippet=SnippetResolver.snippet("systemctl status\n"),
            snippet_anchor=SnippetAnchor.SERVICE,
        )
    )
    container.append(
        UnboundMaintscriptSnippet(
            definition_source="test/2",
            snippet=SnippetResolver.snippet("run foo\n"),
        )
    )
    assert not container.needs_debconf()
    snippet = container.generate_snippet(
        snippet_anchor=SnippetAnchor._BETWEEN_CONFIGURATION_MANAGEMENT_AND_SERVICE,
    )
    assert snippet
    assert "run foo\n" in snippet
    assert "systemctl status\n" not in snippet
    service_snippet = container.generate_snippet(snippet_anchor=SnippetAnchor.SERVICE)
    assert service_snippet
    assert "run foo\n" not in service_snippet
    assert "systemctl status\n" in service_snippet

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

    assert container.needs_debconf()
    snippet = container.generate_snippet(
        snippet_anchor=SnippetAnchor._BETWEEN_CONFIGURATION_MANAGEMENT_AND_SERVICE,
    )
    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_anchor=SnippetAnchor.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(
        snippet_anchor=SnippetAnchor._BETWEEN_CONFIGURATION_MANAGEMENT_AND_SERVICE,
        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
