"""
Importa (ou garante) a revisão de demonstração a partir de `ARCHIVOS_DIR`.

O port antigo do Flask trazia dependências e trechos de SQLAlchemy; esta versão é
intencionalmente mínima e estável para manter o portal funcionando.
"""

from __future__ import annotations

from django.conf import settings

from accounts.models import User
from reviews.models import Review
from rsl.services.seed import setup_new_review

BASE_DIR = settings.BASE_DIR.parent
ARCHIVOS_DIR = getattr(settings, "ARCHIVOS_DIR", BASE_DIR / "sysRevisao" / "arquivos")

__all__ = ["ARCHIVOS_DIR", "import_real_review", "attach_coauthor"]


def import_real_review(owner: User, slug: str = "revisao-demonstracao", *, force: bool = False) -> Review:
    """
    Garante uma revisão de demonstração.

    Se houver arquivos em `ARCHIVOS_DIR`, eles podem ser importados em uma versão
    futura, mas o sistema não deve depender disso para funcionar.
    """
    existing = Review.objects.filter(slug=slug, owner_id=owner.id).order_by("-id").first()
    if existing and force:
        existing.delete()
        existing = None

    if existing:
        return existing

    review = Review.objects.create(
        slug=slug,
        title="Revisão de demonstração",
        owner_id=owner.id,
        description="Revisão de demonstração gerada automaticamente.",
        is_public=True,
        publish_status="P",
        is_demo=True,
    )
    setup_new_review(review)
    review.ensure_search_sessions()
    return review


def attach_coauthor(review: Review) -> None:
    other = User.objects.exclude(pk=review.owner_id).order_by("id").first()
    if other and not review.co_authors.filter(pk=other.pk).exists():
        review.co_authors.add(other)

