import types
import pytest

from pentest_mcp_server.server import PentestMCPServer


class DummySSH:
	async def ensure_connected(self):
		return True

	async def run_command(self, cmd: str, timeout: int | None = None):
		# Determine target path in the simulated command
		# Commands are built as either:
		# ls -la {path} 2>/dev/null || echo 'NOT_FOUND'
		# find {path} -type f -printf ... 2>/dev/null || echo 'NOT_FOUND'
		target_path = None
		if cmd.startswith("ls -la "):
			target_path = cmd.split(" ")[2]
		elif cmd.startswith("find "):
			target_path = cmd.split(" ")[1]

		# Simulate missing path
		if target_path and "does/not/exist" in target_path:
			return types.SimpleNamespace(exit_status=0, stdout="NOT_FOUND\n", stderr="")

		# Simulate successful listing output
		if cmd.startswith("ls -la "):
			return types.SimpleNamespace(exit_status=0, stdout="-rw-r--r-- 1 root root 5 /tmp/a.txt\n", stderr="")
		if cmd.startswith("find "):
			return types.SimpleNamespace(exit_status=0, stdout="/tmp/a.txt 5 1700000000.0\n", stderr="")

		return types.SimpleNamespace(exit_status=0, stdout="", stderr="")


class DummyTmux:
	async def initialize(self):
		return True


@pytest.mark.asyncio
async def test_list_files_success():
	server = PentestMCPServer()
	server.ssh_manager = DummySSH()
	server.tmux_manager = DummyTmux()
	async def ok_init():
		return True
	server._ensure_initialized = ok_init  # type: ignore[attr-defined]

	res = await server._handle_list_files({"path": "/tmp", "recursive": False})
	assert res["status"] == "success"
	assert "output" in res and "/tmp/a.txt" in res["output"]


@pytest.mark.asyncio
async def test_list_files_not_found():
	server = PentestMCPServer()
	server.ssh_manager = DummySSH()
	server.tmux_manager = DummyTmux()
	async def ok_init():
		return True
	server._ensure_initialized = ok_init  # type: ignore[attr-defined]

	res = await server._handle_list_files({"path": "/does/not/exist", "recursive": False})
	assert res["status"] == "error"
	assert "Path not found" in res["message"]
