
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.test import Client
from django.contrib.auth.models import User
from core.models import Bookmark
from django.urls import reverse

def run():
    # Setup
    username = 'debug_user_123'
    password = 'password'
    if User.objects.filter(username=username).exists():
        User.objects.get(username=username).delete()
    
    user = User.objects.create_user(username=username, password=password)
    
    bookmark = Bookmark.objects.create(
        user=user,
        url='https://debug.com',
        title='Debug Bookmark',
        notes='Debug Notes'
    )
    bookmark.tags.add('initial')
    
    print(f"Initial tags: {list(bookmark.tags.names())}")
    
    client = Client()
    client.login(username=username, password=password)
    
    url = reverse('bookmark-edit', args=[bookmark.pk])
    
    # Test Clearing Tags
    data = {
        'url': 'https://debug.com',
        'title': 'Updated Title',
        'notes': 'Updated Notes',
        'tags_input': '', # Empty string
        'is_favorite': False
    }
    
    print(f"Posting to {url} with data: {data}")
    response = client.post(url, data, HTTP_HOST='127.0.0.1')
    
    bookmark.refresh_from_db()
    final_tags = list(bookmark.tags.names())
    print(f"Final tags: {final_tags}")
    
    if final_tags == []:
        print("SUCCESS: Tags cleared correctly.")
    else:
        print("FAILURE: Tags NOT cleared correctly.")
        
    # Cleanup
    bookmark.delete()
    user.delete()

if __name__ == '__main__':
    run()
