"""FRSME-MEI011 — SMEHub indicator dashboard aggregation.

Tests ``smehub_metrics_overview`` and ``smehub_metrics_by_dimension`` against
synthetic fixtures so the dashboard can be trusted across cohort / sector /
country splits.
"""
from __future__ import annotations

from decimal import Decimal

import pytest
from django.contrib.auth import get_user_model

from apps.core.permissions.roles import UserRole
from apps.mel.tracking.models import SMEHubTrackingRecord
from apps.mel.tracking.services_dashboard import (
    smehub_metrics_by_dimension,
    smehub_metrics_overview,
)
from apps.smehub.onboarding.models import Business, BusinessStage, EntrepreneurProfile

User = get_user_model()
pytestmark = pytest.mark.django_db


@pytest.fixture
def admin():
    return User.objects.create_user(
        email="adm-dash@example.com", password="x",
        is_superuser=True, is_staff=True, role=UserRole.SYSTEM_ADMIN,
    )


def _make_entrepreneur(email: str, country: str, admin) -> EntrepreneurProfile:
    user = User.objects.create_user(email=email, password="x", role=UserRole.ENTREPRENEUR)
    profile = EntrepreneurProfile.objects.create(user=user, country=country, organisation="Co")
    profile.verify(by_user=admin)
    profile.save()
    return profile


def _make_business(entrepreneur, name: str, sector: str, country: str, admin) -> Business:
    biz = Business.objects.create(
        entrepreneur=entrepreneur,
        name=name,
        sector=sector,
        business_stage=BusinessStage.MVP,
        country=country,
    )
    biz.verify(by_user=admin)
    biz.save()
    return biz


@pytest.fixture
def fixtures(admin):
    """Build 3 entrepreneurs in 2 sectors, 2 countries — covers all dimensions."""
    e1 = _make_entrepreneur("dash-e1@example.com", "UG", admin)
    b1 = _make_business(e1, "Agri Co", "Agriculture", "UG", admin)
    r1 = SMEHubTrackingRecord.objects.create(
        entrepreneur=e1, business=b1,
        funding_secured_total=Decimal("100000"),
        sp1_baseline_at="2026-01-01T00:00:00Z",
    )

    e2 = _make_entrepreneur("dash-e2@example.com", "UG", admin)
    b2 = _make_business(e2, "Agri Co 2", "Agriculture", "UG", admin)
    r2 = SMEHubTrackingRecord.objects.create(
        entrepreneur=e2, business=b2,
        funding_secured_total=Decimal("50000"),
        sp1_baseline_at="2026-02-01T00:00:00Z",
        is_stalled=True,
    )

    e3 = _make_entrepreneur("dash-e3@example.com", "KE", admin)
    b3 = _make_business(e3, "Tech Co", "Technology", "KE", admin)
    r3 = SMEHubTrackingRecord.objects.create(
        entrepreneur=e3, business=b3,
        funding_secured_total=Decimal("250000"),
    )
    return [r1, r2, r3]


def test_overview_unfiltered(fixtures):
    overview = smehub_metrics_overview()
    assert overview["total_entrepreneurs"] == 3
    assert overview["with_baseline"] == 2
    assert overview["stalled"] == 1
    assert overview["total_funding_secured"] == Decimal("400000")


def test_overview_filtered_by_sector(fixtures):
    overview = smehub_metrics_overview(sector="Agriculture")
    assert overview["total_entrepreneurs"] == 2
    assert overview["stalled"] == 1
    assert overview["total_funding_secured"] == Decimal("150000")


def test_overview_filtered_by_country(fixtures):
    overview = smehub_metrics_overview(country="KE")
    assert overview["total_entrepreneurs"] == 1
    assert overview["total_funding_secured"] == Decimal("250000")


def test_by_sector_returns_rows(fixtures):
    rows = smehub_metrics_by_dimension("sector")
    labels = {row["label"] for row in rows}
    assert "Agriculture" in labels
    assert "Technology" in labels
    ag_row = next(row for row in rows if row["label"] == "Agriculture")
    assert ag_row["entrepreneurs"] == 2
    assert ag_row["funding"] == Decimal("150000")


def test_by_country_drilldown(fixtures):
    rows = smehub_metrics_by_dimension("country")
    labels = {row["label"] for row in rows}
    assert "UG" in labels
    assert "KE" in labels


def test_by_month_buckets_records(fixtures):
    rows = smehub_metrics_by_dimension("month")
    assert len(rows) >= 1  # at least the current month bucket


def test_unknown_dimension_raises(fixtures):
    with pytest.raises(ValueError):
        smehub_metrics_by_dimension("not_a_dimension")
