"""Helpers for User Agreement / Privacy Policy gating and snapshots."""

from __future__ import annotations

from django.utils import timezone

from accounts.models import (
    LegalDocument,
    TransporterProfile,
    UserAgreementAcceptance,
    UserRole,
)


def get_active_legal_document(doc_type: str, locale: str = 'en') -> LegalDocument | None:
    return (
        LegalDocument.objects.filter(
            doc_type=doc_type,
            locale=locale,
            is_active=True,
        )
        .order_by('-effective_at', '-id')
        .first()
    )


def get_active_user_agreement(locale: str = 'en') -> LegalDocument | None:
    return get_active_legal_document(LegalDocument.DocType.USER_AGREEMENT, locale=locale)


def get_active_privacy_policy(locale: str = 'en') -> LegalDocument | None:
    return get_active_legal_document(LegalDocument.DocType.PRIVACY_POLICY, locale=locale)


def legal_snapshot_account_type(user) -> str:
    """
    Spreadsheet / admin filter values:
    SHIPPER | TRANSPORTER (fleet owner) | DRIVER | TRANSPORTER_DRIVER
    """
    try:
        role = user.role.role
    except UserRole.DoesNotExist:
        return ''
    if role == UserRole.Role.SHIPPER:
        return 'SHIPPER'
    if role == UserRole.Role.TRANSPORTER:
        try:
            at = user.transporter_profile.account_type
        except TransporterProfile.DoesNotExist:
            return 'TRANSPORTER'
        if at == TransporterProfile.AccountType.FLEET_OWNER:
            return 'TRANSPORTER'
        if at == TransporterProfile.AccountType.DRIVER:
            return 'DRIVER'
        if at == TransporterProfile.AccountType.TRANSPORTER_DRIVER:
            return 'TRANSPORTER_DRIVER'
        return str(at)
    return str(role)


def user_display_full_name(user) -> str:
    name = f'{user.first_name} {user.last_name}'.strip()
    return name or (user.email or user.get_username() or '')


def user_phone(user) -> str:
    try:
        return user.role.phone or ''
    except UserRole.DoesNotExist:
        return ''


def effective_user_agreement_accepted(user, locale: str = 'en') -> bool:
    """True only when UserRole flag is set AND version matches active USER_AGREEMENT."""
    try:
        role = user.role
    except UserRole.DoesNotExist:
        return False
    if not role.user_agreement_accepted:
        return False
    active = get_active_user_agreement(locale=locale)
    if not active:
        return False
    return (role.user_agreement_version or '') == (active.version or '')


def latest_acceptance_for_active(user, locale: str = 'en') -> UserAgreementAcceptance | None:
    active = get_active_user_agreement(locale=locale)
    if not active:
        return None
    return (
        UserAgreementAcceptance.objects.filter(
            user=user,
            agreement_document=active,
        )
        .order_by('-accepted_at', '-id')
        .first()
    )


def legal_gate_payload(user, request=None, locale: str = 'en') -> dict:
    """Profile / login fields for mobile agreement gate."""
    from api.media_urls import build_absolute_media_url

    try:
        role = user.role
    except UserRole.DoesNotExist:
        role = None

    active_ua = get_active_user_agreement(locale=locale)
    active_pp = get_active_privacy_policy(locale=locale)
    accepted = effective_user_agreement_accepted(user, locale=locale)
    acceptance = latest_acceptance_for_active(user, locale=locale) if accepted else None

    signature_url = None
    if acceptance and acceptance.signature_file:
        signature_url = build_absolute_media_url(
            request,
            acceptance.signature_file.url,
        )

    return {
        'user_agreement_accepted': accepted,
        'user_agreement_accepted_at': (
            role.user_agreement_accepted_at.isoformat()
            if role and role.user_agreement_accepted_at and accepted
            else None
        ),
        'user_agreement_version': (role.user_agreement_version or None) if role and accepted else None,
        'user_agreement_signature_url': signature_url,
        'privacy_policy_version': active_pp.version if active_pp else None,
        'active_user_agreement_version': active_ua.version if active_ua else None,
    }


def legal_document_payload(doc: LegalDocument) -> dict:
    return {
        'doc_type': doc.doc_type,
        'version': doc.version,
        'title': doc.title,
        'body': doc.body,
        'effective_at': doc.effective_at.isoformat() if doc.effective_at else None,
        'locale': doc.locale,
    }


def mark_user_agreement_accepted(user, document: LegalDocument, when=None) -> UserRole:
    when = when or timezone.now()
    role = user.role
    role.user_agreement_accepted = True
    role.user_agreement_accepted_at = when
    role.user_agreement_version = document.version
    role.save(
        update_fields=[
            'user_agreement_accepted',
            'user_agreement_accepted_at',
            'user_agreement_version',
            'updated_at',
        ]
    )
    return role
