import os

import segno
from io import BytesIO

from django.conf import settings
from django.core.files import File
from django.urls import reverse


def generate_qr_code(pin):
    # Use 'reverse' to get the relative URL from the view name and parameters
    relative_url = reverse('visitor_profile', args=[pin])

    # Construct the full URL
    full_url = f"{settings.SITE_BASE_URL}{relative_url}"  # SITE_URL is like 'http://example.com'

    qrcode = segno.make_qr(full_url)

    # Construct the full path to the background image
    background_image_path = os.path.join(settings.BASE_DIR, 'apps/carers/static/media/images/peopleoo-logo.png')

    buffer = BytesIO()

    # Generate artistic QR code
    qrcode.to_artistic(background=background_image_path, target=buffer, scale=25, kind='png')

    buffer.seek(0)
    return File(buffer, name=f"qr_code_{pin}.png")
