"""G19 — MEL Dashboard drill-down filters.

Verifies that ?cohort=&sector=&aih=&country=&period= query params narrow the
aggregates surfaced on the cross-module M&EL dashboard.
"""
from __future__ import annotations

from datetime import date, timedelta
from decimal import Decimal

import pytest
from django.contrib.auth import get_user_model
from django.urls import reverse

from apps.core.permissions.roles import UserRole
from apps.mel.indicators.models import (
    DataPoint,
    Indicator,
    IndicatorFrequency,
    LogFrame,
    LogFrameLevel,
    LogFrameRow,
)

User = get_user_model()


pytestmark = pytest.mark.django_db


@pytest.fixture
def mel_officer():
    return User.objects.create_user(
        email="mel-g19@example.com", password="x", role=UserRole.MEL_OFFICER,
    )


@pytest.fixture
def two_indicators_with_period_data():
    lf = LogFrame.objects.create(name="LF G19", slug="lf-g19")
    impact = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.IMPACT, title="I")
    outcome = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.OUTCOME, title="O", parent=impact)
    output = LogFrameRow.objects.create(logframe=lf, level=LogFrameLevel.OUTPUT, title="P", parent=outcome)
    a = Indicator.objects.create(
        logframe_row=output,
        code="g19-a",
        name="A",
        unit="people",
        calculation_method="count",
        data_source="manual",
        frequency=IndicatorFrequency.QUARTERLY,
    )
    b = Indicator.objects.create(
        logframe_row=output,
        code="g19-b",
        name="B",
        unit="people",
        calculation_method="count",
        data_source="manual",
        frequency=IndicatorFrequency.QUARTERLY,
    )
    # DataPoints for two distinct periods so the period filter can prune.
    DataPoint.objects.create(
        indicator=a, value=Decimal("10"), period_label="2026Q1",
        reported_at=date.today() - timedelta(days=90),
    )
    DataPoint.objects.create(
        indicator=b, value=Decimal("20"), period_label="2026Q2",
        reported_at=date.today() - timedelta(days=10),
    )
    return lf, a, b


def test_dashboard_renders_with_no_filters(client, mel_officer, two_indicators_with_period_data):
    client.force_login(mel_officer)
    resp = client.get(reverse("mel_tracking:tracking_dashboard"))
    assert resp.status_code == 200
    ctx = resp.context
    assert ctx["any_filter_active"] is False
    # Choice helpers are wired.
    assert "cohort_choices" in ctx
    assert "sector_choices" in ctx
    assert "country_choices" in ctx
    assert "aih_choices" in ctx
    assert "period_choices" in ctx
    # Period choices include the two seeded labels.
    period_values = {value for value, _ in ctx["period_choices"]}
    assert {"2026Q1", "2026Q2"} <= period_values


def test_dashboard_period_filter_narrows_recent_datapoints(
    client, mel_officer, two_indicators_with_period_data
):
    client.force_login(mel_officer)
    resp = client.get(reverse("mel_tracking:tracking_dashboard") + "?period=2026Q1")
    assert resp.status_code == 200
    ctx = resp.context
    assert ctx["any_filter_active"] is True
    # Only the Q1 DataPoint is in the recent window summary.
    assert ctx["recent_datapoints"]["total"] == 1


def test_dashboard_clear_link_present_when_filtered(
    client, mel_officer, two_indicators_with_period_data
):
    client.force_login(mel_officer)
    resp = client.get(reverse("mel_tracking:tracking_dashboard") + "?period=2026Q2")
    assert resp.status_code == 200
    # Clear link surfaces in the rendered HTML when any filter is active.
    assert b"Clear" in resp.content
