from __future__ import annotations

from omni.state import StateStore


def test_history_add_and_count() -> None:
    state = StateStore()
    try:
        state.history_add(
            command="omnipy get Clusters.omni.sidero.dev",
            argv=["omnipy", "get", "Clusters.omni.sidero.dev"],
            instance="default",
            cluster="cluster-a",
        )
        assert state.history_count() == 1
        rows = state.history_list(limit=5)
        assert len(rows) == 1
        assert rows[0]["command"].startswith("omnipy get")
        assert rows[0]["instance"] == "default"
        assert rows[0]["cluster"] == "cluster-a"
    finally:
        state.close()


def test_history_prunes_to_limit() -> None:
    state = StateStore()
    try:
        for i in range(6):
            state.history_add(
                command=f"omnipy cmd {i}",
                argv=["omnipy", "cmd", str(i)],
                instance="default",
                cluster=None,
                max_entries=3,
            )
        assert state.history_count() == 3
        rows = state.history_list(limit=10)
        commands = [str(row["command"]) for row in rows]
        assert commands[0] == "omnipy cmd 5"
        assert commands[-1] == "omnipy cmd 3"
    finally:
        state.close()


def test_history_suggest_prefix() -> None:
    state = StateStore()
    try:
        state.history_add(
            command="omnipy get Clusters.omni.sidero.dev",
            argv=["omnipy", "get", "Clusters.omni.sidero.dev"],
            instance="default",
            cluster=None,
        )
        state.history_add(
            command="omnipy get Machines.omni.sidero.dev",
            argv=["omnipy", "get", "Machines.omni.sidero.dev"],
            instance="default",
            cluster=None,
        )
        state.history_add(
            command="omnipy support --cluster c1",
            argv=["omnipy", "support", "--cluster", "c1"],
            instance="default",
            cluster="c1",
        )
        suggestions = state.history_suggest("omnipy get")
        assert suggestions
        assert all(cmd.startswith("omnipy get") for cmd in suggestions)
    finally:
        state.close()

