"""Native tests for analytics parsing helpers."""

from __future__ import annotations

from typing import Any
from unittest.mock import AsyncMock, MagicMock

import pytest

from timeback_edubridge import aggregate_activity_metrics
from timeback_edubridge.resources.analytics import (
    AnalyticsResource,
    _parse_daily_activity_map,
    _parse_weekly_facts,
)
from timeback_edubridge.types.analytics import SubjectMetrics, WeeklyFactRecord


def _raw_subject_metrics() -> dict[str, Any]:
    return {
        "activityMetrics": {
            "xpEarned": 100,
            "totalQuestions": 50,
            "correctQuestions": 45,
            "masteredUnits": 10,
        },
        "timeSpentMetrics": {"activeSeconds": 3600, "inactiveSeconds": 300, "wasteSeconds": 60},
        "apps": ["TestApp"],
    }


def _raw_weekly_fact() -> dict[str, Any]:
    return {
        "id": 12345,
        "email": "student@example.com",
        "date": "2026-01-29",
        "datetime": "2026-01-29T10:00:00Z",
        "source": "activity",
        "year": 2026,
        "month": 1,
        "day": 29,
        "dayOfWeek": 3,
    }


def _stub_transport(response: dict[str, Any]) -> MagicMock:
    transport = MagicMock()
    transport.get = AsyncMock(return_value=response)
    transport.paths = MagicMock()
    transport.paths.base = "/edubridge"
    return transport


def test_parse_daily_activity_map_produces_typed_subject_metrics() -> None:
    result = _parse_daily_activity_map({"2026-01-29": {"Math": _raw_subject_metrics()}})
    assert isinstance(result["2026-01-29"]["Math"], SubjectMetrics)


def test_parse_weekly_facts_produces_typed_records() -> None:
    result = _parse_weekly_facts([_raw_weekly_fact()])
    assert isinstance(result[0], WeeklyFactRecord)


@pytest.mark.asyncio
async def test_get_activity_output_works_with_aggregation() -> None:
    transport = _stub_transport({"facts": {"2026-01-29": {"Math": _raw_subject_metrics()}}})
    facts = await AnalyticsResource(transport).get_activity(  # type: ignore[arg-type]
        email="test@example.com",
        start_date="2026-01-29",
        end_date="2026-01-30",
    )
    result = aggregate_activity_metrics(facts)
    assert result.mastered_units == 10


@pytest.mark.asyncio
async def test_get_weekly_facts_returns_typed_records() -> None:
    transport = _stub_transport({"facts": [_raw_weekly_fact()]})
    result = await AnalyticsResource(transport).get_weekly_facts(  # type: ignore[arg-type]
        email="test@example.com",
        week_date="2026-01-29",
    )
    assert isinstance(result[0], WeeklyFactRecord)
