import json

import pytest


def test_document_tools_validate_inputs_and_format_outputs(
    tools, cognite_client_mock, dumpable_factory
) -> None:
    with pytest.raises(ValueError, match="non-empty list"):
        tools["ask_documents_question"](question="q", file_instance_ids="[]")

    cognite_client_mock.ai.tools.documents.ask_question.return_value = dumpable_factory(
        {"answer": "ok"}
    )
    valid_answer = json.loads(
        tools["ask_documents_question"](
            question="q",
            file_instance_ids='[{"space": "docs", "externalId": "doc-1"}]',
            ignore_unknown_ids=True,
        )
    )
    ask_kwargs = cognite_client_mock.ai.tools.documents.ask_question.call_args.kwargs
    assert ask_kwargs["instance_id"][0].space == "docs"
    assert ask_kwargs["instance_id"][0].external_id == "doc-1"
    assert valid_answer["answer"] == "ok"

    with pytest.raises(ValueError, match="instance_id is required"):
        tools["summarize_document"](instance_id=None)

    cognite_client_mock.ai.tools.documents.summarize.return_value = "brief"
    valid_summary = json.loads(
        tools["summarize_document"](instance_id={"space": "docs", "externalId": "doc-1"})
    )
    summarize_kwargs = cognite_client_mock.ai.tools.documents.summarize.call_args.kwargs
    assert summarize_kwargs["instance_id"].external_id == "doc-1"
    assert valid_summary["summary"] == "brief"


def test_document_tools_propagate_sdk_errors(tools, cognite_client_mock) -> None:
    cognite_client_mock.ai.tools.documents.ask_question.side_effect = RuntimeError("ask failed")
    with pytest.raises(RuntimeError, match="ask failed"):
        tools["ask_documents_question"](
            question="q",
            file_instance_ids='[{"space": "docs", "externalId": "doc-1"}]',
        )

    cognite_client_mock.ai.tools.documents.summarize.side_effect = RuntimeError("summarize failed")
    with pytest.raises(RuntimeError, match="summarize failed"):
        tools["summarize_document"](instance_id={"space": "docs", "externalId": "doc-1"})
