"""Cross-app helper — surface relevant Repository documents to entrepreneurs.

PRD §5.2 (REPO) says "SME Hub innovators draw on Repository content to
inform product development". The Repository is the source of truth for
research outputs; this helper just builds the *query* that turns an
entrepreneur's business profile into a ranked list of public Repository
documents that match their sector keywords.

Kept here in ``_shared`` (not under repository.documents) because:
* the SME-Hub side owns the matching policy (sector / keywords / country),
* the Repository app is upstream and shouldn't know about Business at all.
"""
from __future__ import annotations

from django.db.models import Q


def relevant_repository_documents(business, *, limit: int = 10):
    """Return a queryset of published, public-or-authenticated Repository
    documents most relevant to ``business``.

    Match policy (in priority order):
      1. Documents tagged with a Keyword whose ``label`` matches the
         business ``sector`` (case-insensitive).
      2. Recent documents in the same ``Collection`` tree.

    Returns an empty list when the Repository app is unavailable, the
    business has no sector, or no documents match — never raises.
    """
    if business is None or not getattr(business, "sector", None):
        return []
    try:
        from apps.repository.documents.models import Document, Keyword
    except ImportError:
        return []

    sector = (business.sector or "").strip()
    if not sector:
        return []

    keyword_ids = list(
        Keyword.objects.filter(
            status=Keyword.Status.APPROVED,
        ).filter(
            Q(label__iexact=sector) | Q(slug__iexact=sector.lower().replace(" ", "-")),
        ).values_list("pk", flat=True),
    )

    qs = Document.objects.filter(
        status=Document.Status.PUBLISHED,
    ).exclude(
        visibility=Document.Visibility.RESTRICTED,
    ).exclude(
        visibility=Document.Visibility.INTERNAL,
    )
    if keyword_ids:
        qs = qs.filter(keywords__in=keyword_ids).distinct()
    return qs.order_by("-year", "-id")[:limit]
