import re

file_path = 'core/views.py'

with open(file_path, 'r') as f:
    content = f.read()

# 1. Add Device to imports
if 'Device' not in content:
    pattern = r'(from \.models import \(.*?)(\))'
    replacement = r'\1, Device\2'
    content = re.sub(pattern, replacement, content, flags=re.DOTALL)
    print("Added Device to imports.")

# 2. Update settings_view
if 'devices = Device.objects.all()' not in content:
    # Find the lines before context creation
    search_str = 'loyalty_tiers = LoyaltyTier.objects.all().order_by("min_points")'
    insert_str = '\n    devices = Device.objects.all().order_by("name")'
    content = content.replace(search_str, search_str + insert_str)
    
    # Update context
    context_search = '"loyalty_tiers": loyalty_tiers'
    context_insert = ',\n        "devices": devices'
    content = content.replace(context_search, context_search + context_insert)
    print("Updated settings_view.")

# 3. Add Device views
new_views = """

@login_required
def add_device(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        device_type = request.POST.get('device_type')
        connection_type = request.POST.get('connection_type')
        ip_address = request.POST.get('ip_address')
        port = request.POST.get('port')
        is_active = request.POST.get('is_active') == 'on'
        
        Device.objects.create(
            name=name,
            device_type=device_type,
            connection_type=connection_type,
            ip_address=ip_address if ip_address else None,
            port=port if port else None,
            is_active=is_active
        )
        messages.success(request, _("Device added successfully!"))
    return redirect(reverse('settings') + '#devices')

@login_required
def edit_device(request, pk):
    device = get_object_or_404(Device, pk=pk)
    if request.method == 'POST':
        device.name = request.POST.get('name')
        device.device_type = request.POST.get('device_type')
        device.connection_type = request.POST.get('connection_type')
        device.ip_address = request.POST.get('ip_address')
        device.port = request.POST.get('port')
        device.is_active = request.POST.get('is_active') == 'on'
        
        if not device.ip_address:
            device.ip_address = None
        if not device.port:
            device.port = None
            
        device.save()
        messages.success(request, _("Device updated successfully!"))
    return redirect(reverse('settings') + '#devices')

@login_required
def delete_device(request, pk):
    device = get_object_or_404(Device, pk=pk)
    device.delete()
    messages.success(request, _("Device deleted successfully!"))
    return redirect(reverse('settings') + '#devices')
"""

if 'def add_device(request):' not in content:
    content += new_views
    print("Added Device views.")

with open(file_path, 'w') as f:
    f.write(content)