import pytest


def test_tool_executor_blocks_disallowed_tool_with_typed_error(tmp_path):
    from api.services.tool_executor import ToolExecutor, ToolExecutionError

    ws = tmp_path / "ws"
    ws.mkdir()
    te = ToolExecutor(workspace_root=str(ws))

    with pytest.raises(ToolExecutionError) as e:
        te.execute_tool(
            "Write",
            {
                "path": "x.txt",
                "content": "hi",
                "__capabilities": {"allowed_tools": ["read"]},
            },
        )

    err = e.value
    assert getattr(err, "code", None) == "PERMISSION_DENIED"


def test_detect_capability_contradiction_flags_cant_edit_when_allowed():
    from api.services.agent_capabilities import AgentCapabilities, detect_capability_contradiction

    caps = AgentCapabilities.from_tools_schema(
        tools=[
            {"type": "function", "function": {"name": "Write", "parameters": {"type": "object", "properties": {}}}}
        ],
        tool_execution_location="client",
    )
    why = detect_capability_contradiction("I can't modify files here.", caps)
    assert why is not None


def test_proof_validator_requires_ledger_reference_for_tool_claim():
    from api.services.proof_carrying_validator import validate_assistant_proof

    r = validate_assistant_proof(
        assistant_text="The grep shows compression_ratio defaults to 1.0.",
        context_text="",
        context_manifest={},
        valid_ledger_ids=[],
        ledger_tool_names={},
    )
    assert r.ok is False


def test_execution_ledger_mints_deterministic_id():
    from api.services.execution_ledger import make_ledger_record

    r1 = make_ledger_record(
        request_id="req1",
        tool_call_id="call1",
        tool_name="Grep",
        tool_args={"pattern": "x"},
        tool_result_content={"match_count": 0},
    )
    r2 = make_ledger_record(
        request_id="req1",
        tool_call_id="call1",
        tool_name="Grep",
        tool_args={"pattern": "x"},
        tool_result_content={"match_count": 0},
    )
    assert r1.ledger_id == r2.ledger_id
    assert r1.ledger_id.startswith("led_")

