"""Cross-survey tracer insight aggregation for the alumni impact report."""
from __future__ import annotations

import pytest

from apps.alumni.profiles.models import AlumniProfile
from apps.alumni.tracking.services_impact_survey import (
    aggregate_tracer_insights,
    launch_impact_survey,
)
from apps.mel.feedback.models import SurveyAnswer, SurveyDispatch, SurveyResponse


@pytest.mark.django_db
def test_aggregate_tracer_insights_empty():
    insights = aggregate_tracer_insights()
    assert insights["has_data"] is False
    assert insights["total_completed"] == 0


@pytest.mark.django_db
def test_aggregate_tracer_insights_from_responses(alumni_user):
    AlumniProfile.objects.get_or_create(user=alumni_user)
    survey = launch_impact_survey(title="Insights Test Tracer", created_by=None)

    q = {question.text: question for question in survey.questions.all()}
    dispatch = SurveyDispatch.objects.filter(
        survey=survey, recipient=alumni_user
    ).first()
    assert dispatch is not None  # cohort had our alumnus

    response = SurveyResponse.objects.create(
        survey=survey,
        dispatch=dispatch,
        respondent=alumni_user,
        status=SurveyResponse.Status.COMPLETED,
    )

    def answer(text, value, free=""):
        SurveyAnswer.objects.create(
            response=response, question=q[text], value={"value": value}, free_text=free
        )

    answer("What is your current employment status?", "employed_ft")
    answer("How has your income changed since graduating?", "increased_significantly")
    answer("Have you undertaken further study since graduating?", "true")
    answer("How relevant was your RUFORUM training to your current work?", "5")
    answer("What sector do you currently work in?", "Research", "Research")

    insights = aggregate_tracer_insights()
    assert insights["has_data"] is True
    assert insights["total_completed"] == 1
    assert insights["employed_pct"] == 100.0
    assert insights["further_study_yes_pct"] == 100.0
    assert insights["training_relevance_mean"] == 5.0
    # employment distribution surfaces the labelled top outcome
    assert insights["employment"][0]["value"] == "employed_ft"
    assert insights["employment"][0]["label"] == "Employed full-time"
    assert {s["label"] for s in insights["top_sectors"]} == {"Research"}


@pytest.mark.django_db
def test_group_list_marks_joined(client, alumni_user):
    from apps.alumni.engagement.models import GroupMembership, NetworkGroup
    from django.urls import reverse

    joined = NetworkGroup.objects.create(title="Joined Group")
    other = NetworkGroup.objects.create(title="Other Group")
    GroupMembership.objects.create(user=alumni_user, group=joined, role="member")

    client.force_login(alumni_user)
    resp = client.get(reverse("alumni_engagement:network_group_list"))
    assert resp.status_code == 200
    assert joined.pk in resp.context["joined_group_ids"]
    assert other.pk not in resp.context["joined_group_ids"]
    assert resp.context["joined_count"] == 1
