from __future__ import annotations

from pytest import approx

from worai.seoreport.analytics import allocate_direct_share


def test_allocate_direct_share_reallocates_direct():
    total = {
        "sessions": 100,
        "totalUsers": 80,
        "engagedSessions": 60,
        "averageSessionDuration": 10,
        "screenPageViews": 200,
    }
    ai_raw = {
        "sessions": 5,
        "totalUsers": 4,
        "engagedSessions": 3,
        "averageSessionDuration": 12,
        "screenPageViews": 8,
    }
    direct_raw = {
        "sessions": 20,
        "totalUsers": 15,
        "engagedSessions": 10,
        "averageSessionDuration": 5,
        "screenPageViews": 30,
    }

    totals = allocate_direct_share(total, ai_raw, direct_raw, 0.3)

    assert totals["ai"]["sessions"] == approx(11)
    assert totals["direct"]["sessions"] == approx(14)
    assert totals["web"]["sessions"] == approx(89)
    assert totals["total"]["sessions"] == approx(100)

    assert totals["ai"]["engagement_rate"] == approx(6 / 11)
    assert totals["web"]["engagement_rate"] == approx(54 / 89)
    assert totals["ai"]["avg_session_duration"] == approx(90 / 11)
