"""Test that sequential steps chain output via $prev."""

import asyncio
from agenlang.contract import Contract
from agenlang.runtime import Runtime


CONTRACT_DATA = {
    "agenlang_version": "1.0",
    "contract_id": "urn:agenlang:exec:aaaabbbbccccddddaaaabbbbccccdddd",
    "issuer": {"agent_id": "test-chain", "pubkey": "test-pubkey"},
    "goal": "Test chained output",
    "intent_anchor": {"hash": "test-hash"},
    "constraints": {"joule_budget": 1000},
    "workflow": {
        "type": "sequence",
        "steps": [
            {"action": "tool", "target": "web_search", "args": {"query": "Python"}},
            {"action": "tool", "target": "summarize", "args": {"text": "$prev"}},
        ],
    },
    "memory_contract": {
        "handoff_keys": ["web_search"],
        "ttl": "1h",
        "purge_on_complete": True,
        "data_subject": "test-user",
    },
    "settlement": {"joule_recipient": "test", "rate": 1.0},
    "capability_attestations": [
        {"capability": "net:read", "proof": "test"},
        {"capability": "compute:read", "proof": "test"},
    ],
    "ser_config": {},
}


def test_summarize_receives_search_output():
    contract = Contract.from_dict(CONTRACT_DATA)
    runtime = Runtime(contract)
    result, ser = asyncio.run(runtime.execute())

    assert len(runtime.replay_data) == 2
    search_output = runtime.replay_data[0]["output"]
    summary_output = runtime.replay_data[1]["output"]

    # Summary must be derived from search output, not a placeholder
    assert "Dummy" not in search_output
    assert "Dummy" not in summary_output
    assert "$prev" not in summary_output
    # Summary is a truncation of search output (first 100 chars + "...")
    expected_summary = search_output[:100].strip() + "..." if len(search_output) > 100 else search_output.strip()
    assert summary_output == expected_summary
