"""
Analytics Service — Pytest Fixtures.

فیکسچرهای مشترک برای تست‌های سرویس تحلیل و گزارش‌گیری.
"""
import sys
from pathlib import Path
import uuid
from datetime import date
from decimal import Decimal
from django.utils import timezone

PROJECT_ROOT = str(Path(__file__).resolve().parent.parent.parent.parent)
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

import pytest

from apps.core.tenant.models import Tenant, Domain
from apps.core.tenant.middleware import _thread_locals
from apps.core.auth.models import User

# Force import of Analytics views before tests
import apps.services.analytics.views  # noqa: F401

from apps.services.analytics.models import (
    AggregationDefinition,
    AggregationSnapshot,
    KPIRollup,
    ReportTemplate,
    GeneratedReport,
)


# ─── Tenant & Auth ──────────────────────────────────────────

@pytest.fixture(autouse=True)
def _patch_tenant_middleware(tenant, monkeypatch):
    from django.db import connection
    from apps.core.tenant import middleware as tenant_mw

    monkeypatch.setattr(tenant_mw, "get_current_tenant", lambda: tenant)
    if hasattr(connection, "set_tenant"):
        connection.set_tenant(tenant)
    yield
    if hasattr(_thread_locals, "tenant"):
        del _thread_locals.tenant
    if hasattr(_thread_locals, "request"):
        del _thread_locals.request


@pytest.fixture(scope="function")
def tenant(db):
    t = Tenant.objects.create(
        name="Analytics Test Tenant",
        slug="analytics-test",
        schema_name="public",
    )
    Domain.objects.create(domain="localhost", tenant=t, is_primary=True)
    return t


@pytest.fixture
def user(tenant):
    return User.objects.create_user(
        email="anl-user@example.com",
        password="testpass123",
        first_name="Analytics",
        last_name="User",
        tenant=tenant,
    )


@pytest.fixture
def admin_user(tenant):
    return User.objects.create_superuser(
        email="anl-admin@example.com",
        password="adminpass123",
        first_name="Analytics",
        last_name="Admin",
        tenant=tenant,
    )


@pytest.fixture
def api_client():
    from rest_framework.test import APIClient
    return APIClient()


@pytest.fixture
def auth_client(api_client, admin_user):
    api_client.force_authenticate(user=admin_user)
    return api_client


# ─── Analytics Domain Objects ───────────────────────────────

@pytest.fixture
def aggregation_definition(tenant):
    return AggregationDefinition.objects.create(
        id=uuid.uuid4(), tenant=tenant,
        name="تعداد پروژه‌های فعال",
        source_module="pm",
        source_entity="project",
        aggregation_type="count",
        aggregation_field="id",
        filter_criteria={"status": "active"},
        schedule="daily",
        is_active=True,
    )


@pytest.fixture
def aggregation_snapshot(tenant, aggregation_definition):
    return AggregationSnapshot.objects.create(
        id=uuid.uuid4(), tenant=tenant,
        definition=aggregation_definition,
        snapshot_date=date.today(),
        data={"count": 42, "details": []},
        record_count=42,
        execution_time_ms=150,
    )


@pytest.fixture
def kpi_rollup(tenant):
    return KPIRollup.objects.create(
        id=uuid.uuid4(), tenant=tenant,
        kpi_code="KPI-PCT",
        kpi_name="نرخ تکمیل پروژه",
        level="organization",
        period="2026-Q1",
        value=Decimal("78.5000"),
        previous_value=Decimal("72.0000"),
        target_value=Decimal("85.0000"),
        trend="up",
        change_percentage=Decimal("9.03"),
    )


@pytest.fixture
def report_template(tenant, admin_user):
    return ReportTemplate.objects.create(
        id=uuid.uuid4(), tenant=tenant,
        name="گزارش وضعیت پروژه‌ها",
        description="گزارش هفتگی",
        modules=["pm", "ppm"],
        query_definition={"entities": ["project", "portfolio"]},
        default_format="pdf",
        is_scheduled=True,
        schedule="0 8 * * 1",
        owner=admin_user,
        is_active=True,
    )


@pytest.fixture
def generated_report(tenant, report_template, admin_user):
    return GeneratedReport.objects.create(
        id=uuid.uuid4(), tenant=tenant,
        template=report_template,
        title="گزارش هفته ۱۰",
        format="pdf",
        status="completed",
        generated_by=admin_user,
        generated_at=timezone.now(),
    )
