import os
import json
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

def run():
    # Setup
    username = 'api_debug_user'
    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://api-debug.com',
        title='API 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 = f'/api/bookmarks/{bookmark.id}/'
    
    # Test 1: Update tags and title
    data = {
        'tags': ['new', 'tags'],
        'title': 'Updated Title'
    }
    
    print(f"PATCHing to {url} with data: {data}")
    response = client.patch(
        url, 
        json.dumps(data), 
        content_type='application/json',
        HTTP_HOST='127.0.0.1'
    )
    
    print(f"Response status: {response.status_code}")
    
    bookmark.refresh_from_db()
    final_tags = sorted(list(bookmark.tags.names()))
    final_title = bookmark.title
    print(f"Final tags: {final_tags}")
    print(f"Final title: {final_title}")
    
    success = True
    if final_tags != ['new', 'tags']:
        print("FAILURE: API Tags NOT updated correctly.")
        success = False
    else:
        print("SUCCESS: API Tags updated correctly.")
        
    if final_title != 'Updated Title':
        print("FAILURE: API Title NOT updated correctly.")
        success = False
    else:
        print("SUCCESS: API Title updated correctly.")

    # Cleanup
    if success:
        print("All tests passed.")
    else:
        print("Some tests failed.")
        
    bookmark.delete()
    user.delete()

if __name__ == '__main__':
    run()