from __future__ import annotations

from oasyce.services.portfolio_ledger import get_portfolio_ledger_store


def test_portfolio_ledger_tracks_spend_and_recent_entries(tmp_path):
    ledger = get_portfolio_ledger_store(str(tmp_path))
    ledger.record(
        action="register",
        status="succeeded",
        item_id="item-reg",
        account_id="oasyce1owner",
        asset_id="asset_123",
        file_path="/tmp/repo/README.md",
        price_model="free",
        asset_class="open_source_source",
        portfolio_policy_reason="public_git_open_source_defaults_free",
        actor={"device_id": "device-a", "agent_id": "autonomy.executor", "session_id": "run-1"},
        timestamp=1,
    )
    ledger.record(
        action="purchase",
        status="succeeded",
        item_id="item-buy",
        account_id="oasyce1owner",
        asset_id="cap_123",
        debit_oas=7.5,
        actor={"device_id": "device-a", "agent_id": "autonomy.executor", "session_id": "run-1"},
        timestamp=2,
    )

    summary = ledger.summary()

    assert summary["totals"]["entries"] == 2
    assert summary["totals"]["assets_created"] == 1
    assert summary["totals"]["purchases"] == 1
    assert summary["totals"]["spent_oas"] == 7.5
    assert summary["totals"]["net_oas"] == -7.5
    assert summary["contributions"]["delegates"][0]["delegate_id"] == "device-a"
    assert summary["contributions"]["delegates"][0]["agent_counts"]["autonomy.executor"] == 2
    assert summary["recent"][0]["action"] == "purchase"
    assert summary["recent"][0]["actor"]["agent_id"] == "autonomy.executor"
