"""Check sequencing, actual prompt delivery, and failure before model execution."""

from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda
from langsmith import tracing_context

from first_chain import INFORMATION, REPLY, make_chain


def main():
    prompt, chain = make_chain()
    result = chain.invoke({"information": INFORMATION})
    assert isinstance(result, AIMessage)
    assert result.content == REPLY

    received = []

    def capture(prompt_value):
        received.append(prompt_value.to_string())
        return AIMessage(content="Captured, not generated.")

    inspected_chain = prompt | RunnableLambda(capture)
    inspected_chain.invoke({"information": "A new input."})
    assert received == [
        "Summarize only the supplied information in one sentence.\n"
        "Information: A new input."
    ]
    assert "{information}" not in received[0]

    try:
        inspected_chain.invoke({"info": "Wrong input key."})
    except KeyError:
        pass
    else:
        raise AssertionError("The missing variable should fail.")
    assert len(received) == 1, "Invalid input must fail before the model step."
    print("PASS: message output, prompt delivery, and missing-key failure order.")


if __name__ == "__main__":
    with tracing_context(enabled=False):
        main()
