"""Analytics utilities — called from other apps to enrich visitor profiles."""


def stitch_visitor(request, lead):
    """
    Link the current session's VisitorProfile to a converted lead and
    backfill any identity fields (email, name, phone) that were just revealed.
    Safe to call from any view; fails silently.
    """
    try:
        from .models import VisitorProfile
        session_key = getattr(request.session, 'session_key', None)
        if not session_key:
            return
        profile = VisitorProfile.objects.filter(session_key=session_key).first()
        if not profile:
            return

        update = {}
        if not profile.email and getattr(lead, 'email', ''):
            update['email'] = lead.email
        if not profile.name and getattr(lead, 'name', ''):
            update['name'] = lead.name
        if not profile.phone and getattr(lead, 'phone', ''):
            update['phone'] = lead.phone
        if not profile.lead_id:
            update['lead'] = lead
        if not profile.converted:
            update['converted'] = True

        if update:
            for k, v in update.items():
                setattr(profile, k, v)
            profile.save(update_fields=list(update.keys()))
    except Exception:
        pass
