from __future__ import annotations

import os

from legal_mcp.services import claude_session as cs


def test_clean_env_strips_session_markers(monkeypatch):
    """Nested claude -p must not inherit the parent session markers (#85)."""
    for k in (
        "CLAUDECODE",
        "CLAUDE_CODE_ENTRYPOINT",
        "CLAUDE_CODE_SESSION_ID",
        "CLAUDE_CODE_EXECPATH",
        "CLAUDE_CODE_SSE_PORT",
        "CLAUDE_AGENT_SDK_VERSION",
        "AI_AGENT",
        "CLAUDE_EFFORT",
    ):
        monkeypatch.setenv(k, "x")

    env = cs._clean_subprocess_env()

    assert "CLAUDECODE" not in env
    assert "AI_AGENT" not in env
    assert "CLAUDE_EFFORT" not in env
    assert not any(k.startswith("CLAUDE_CODE_") for k in env)
    assert not any(k.startswith("CLAUDE_AGENT_") for k in env)


def test_clean_env_keeps_auth_and_path(monkeypatch):
    """Auth/config + PATH/HOME must survive — they are needed by the CLI."""
    monkeypatch.setenv("CLAUDECODE", "1")
    monkeypatch.setenv("CLAUDE_CONFIG_DIR", "/home/chaim/.claude")
    monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://example")
    monkeypatch.setenv("PATH", os.environ.get("PATH", "/usr/bin"))

    env = cs._clean_subprocess_env()

    # CLAUDE_CONFIG_DIR carries credentials — must NOT be stripped.
    assert env.get("CLAUDE_CONFIG_DIR") == "/home/chaim/.claude"
    assert env.get("ANTHROPIC_BASE_URL") == "https://example"
    assert "PATH" in env
    assert "CLAUDECODE" not in env
