import os
import sys

import django

# Setup Django environment
sys.path.append("/Volumes/macminissd/Projects/thrillwiki_django_no_react/backend")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.django.local")
django.setup()

from django.contrib.auth import get_user_model  # noqa: E402
from rest_framework.test import APIClient  # noqa: E402

from apps.parks.models import Park  # noqa: E402

User = get_user_model()


def run_verification():
    print("Starting Backend Verification...")

    # 1. Create Test User
    username = "verify_user"
    email = "verify@example.com"
    password = "password123"

    user, created = User.objects.get_or_create(username=username, email=email)
    user.set_password(password)
    user.save()
    print(f"User created: {user.username}")

    # 2. Authenticate
    client = APIClient()
    client.force_authenticate(user=user)
    print("Authenticated.")

    # 3. Verify Profile Update (Unit System)
    # Endpoint: /api/v1/auth/user/ or /api/v1/accounts/me/ (depending on dj-rest-auth)
    # Let's try updating profile via PATCH /api/v1/auth/user/
    update_data = {"unit_system": "imperial", "location": "Test City, TS"}
    # Note: unit_system expects 'metric', 'imperial'.
    # Check if 'imperial' is valid key in RichChoiceField.
    # Assuming it is based on implementation plan.

    response = client.patch("/api/v1/accounts/profile/update/", update_data, format="json")
    if response.status_code == 200:
        print(f"Profile updated successfully: {response.data.get('unit_system')}")
        if response.data.get("unit_system") != "imperial":
            print(f"WARNING: unit_system mismatch. Got {response.data.get('unit_system')}")
    else:
        print(f"FAILED to update profile: {response.status_code} {response.data}")

    # 4. Verify UserList CRUD
    # Create List
    list_data = {
        "title": "My Favorite Coasters",
        "category": "RC",  # Roller Coaster
        "description": "Best rides ever",
        "is_public": True,
    }
    response = client.post("/api/v1/lists/lists/", list_data, format="json")
    if response.status_code == 201:
        list_id = response.data["id"]
        print(f"UserList created: {list_id} - {response.data['title']}")
    else:
        print(f"FAILED to create UserList: {response.status_code} {response.data}")
        return

    # Add Item to List
    # We need a content object (Park). Verify if any park exists.
    park = Park.objects.first()
    if not park:
        print("Creating dummy park for testing...")
        park = Park.objects.create(name="Test Park", slug="test-park", country="US")

    # Note: Serializer might expect 'content_type' as ID or string.
    # Let's try string first if using slug-based or app-label based lookup.
    # If standard serializer, might be tricky.
    # Alternatively, use specialized endpoint or just test UserList creation for now.

    # Actually, let's just check if we can GET the list
    response = client.get(f"/api/v1/lists/lists/{list_id}/")
    if response.status_code == 200:
        print(f"UserList retrieved: {response.data['title']}")
    else:
        print(f"FAILED to retrieve UserList: {response.status_code} {response.data}")

    print("Verification Complete.")


if __name__ == "__main__":
    run_verification()
