# Fit one equation per node, then trace paths through the fitted model.
function posteriors(d)
    on, off = d.bid, .!d.bid
    (search = nig_posterior(d.search, d.tv),
     social = nig_posterior(d.social, d.search),
     paid   = nig_posterior(d.paid[on], d.search[on]; intercept = false),
     org_on = nig_posterior(d.org[on], d.search[on]; intercept = false),
     org_off= nig_posterior(d.org[off], d.search[off]; intercept = false),
     cpc    = nig_posterior(d.brand[on], d.paid[on]; intercept = false),
     sales  = nig_posterior(d.sales, d.tv, d.social, d.paid .+ d.org))
end

# One pass of the accounting, given one set of coefficients
function account(â, ĉ, ŝp, ŝon, ŝoff, ĉpc, b̂1, b̂2, v̂)
    per_search_on  = v̂ * (ŝp + ŝon)        # sales per branded search while bidding
    per_search_off = v̂ * ŝoff
    tv_sales(ps, follow) = b̂1 + â * (ps + follow * ĉ * b̂2)
    tv_cost(bill, follow) = 1 + â * (bill + follow * ĉ)
    bill = ŝp * ĉpc                          # branded search spend per branded search
    (tv_on_frozen  = tv_sales(per_search_on, 0),  tv_on_follow  = tv_sales(per_search_on, 1),
     tv_off_frozen = tv_sales(per_search_off, 0), tv_off_follow = tv_sales(per_search_off, 1),
     roi_on_frozen  = tv_sales(per_search_on, 0) / tv_cost(bill, 0),
     roi_on_follow  = tv_sales(per_search_on, 1) / tv_cost(bill, 1),
     roi_off_frozen = tv_sales(per_search_off, 0) / tv_cost(0, 0),
     roi_off_follow = tv_sales(per_search_off, 1) / tv_cost(0, 1),
     social = b̂2, bid_value = per_search_on - per_search_off - bill,
     brand_per_euro = (per_search_on - per_search_off) / bill)
end

function account_draw(P)
    s = draw(P.sales)
    account(draw(P.search)[2], draw(P.social)[2], draw(P.paid)[1], draw(P.org_on)[1],
            draw(P.org_off)[1], draw(P.cpc)[1], s[2], s[3], s[4])
end

account_mean(P) = account(P.search.m[2], P.social.m[2], P.paid.m[1], P.org_on.m[1],
                          P.org_off.m[1], P.cpc.m[1], P.sales.m[2], P.sales.m[3], P.sales.m[4])

truth() = account(a, c, share_paid.on, share_org.on, share_org.off, cpc, b1, b2, v)
