from pathlib import Path
import re


ROOT = Path(__file__).resolve().parents[1]
MCP_COMPOSE = ROOT / "docker-compose.mcp.yml"


def _service_block(compose: str, service_name: str) -> str:
    match = re.search(
        rf"^  {re.escape(service_name)}:\n(?P<body>.*?)(?=^  [A-Za-z0-9_-]+:\n|\Z)",
        compose,
        flags=re.MULTILINE | re.DOTALL,
    )
    assert match, f"{service_name} service block missing"
    return match.group("body")


def test_mcp_http_services_keep_healthchecks():
    compose = MCP_COMPOSE.read_text(encoding="utf-8")

    for service_name in ["postgres-mcp", "mcp-omnisearch", "firecrawl-self"]:
        block = _service_block(compose, service_name)
        assert "healthcheck:" in block
        assert "wget" in block
        assert "/health" in block


def test_firecrawl_stack_keeps_memory_guardrails():
    compose = MCP_COMPOSE.read_text(encoding="utf-8")

    assert "memory: 2g" in _service_block(compose, "firecrawl-self")
    assert "memory: 1.5g" in _service_block(compose, "firecrawl-playwright")
    assert "memory: 128m" in _service_block(compose, "firecrawl-redis")
    assert "memory: 128m" in _service_block(compose, "filesystem-mcp")


def test_filesystem_mcp_stays_read_only():
    compose = MCP_COMPOSE.read_text(encoding="utf-8")
    block = _service_block(compose, "filesystem-mcp")

    assert "ALLOWED_PATHS=/data,/logs" in block
    assert "./data:/data:ro" in block
    assert "./logs:/logs:ro" in block
    assert ":rw" not in block
    assert "/var/run/docker.sock" not in block
