#!/usr/bin/env python3
"""
Debug script to check the PATCH endpoint response
"""
import asyncio
import httpx
import json

async def test():
    base_url = "http://sf_api:8000"
    
    print("1. Logging in...")
    async with httpx.AsyncClient(timeout=30.0) as client:
        # Login
        login_data = {
            "username": "tester_pro@profibot.hu",
            "password": "Password123!"
        }
        
        resp = await client.post(
            f"{base_url}/api/v1/auth/login",
            data=login_data
        )
        print(f"Login status: {resp.status_code}")
        if resp.status_code != 200:
            print(f"Login response: {resp.text}")
            return
        
        login_result = resp.json()
        initial_token = login_result["access_token"]
        print(f"Initial token: {initial_token[:50]}...")
        
        # Test PATCH
        print("\n2. Testing PATCH /users/me/active-organization...")
        headers = {"Authorization": f"Bearer {initial_token}", "Content-Type": "application/json"}
        patch_data = {"organization_id": None}
        
        resp = await client.patch(
            f"{base_url}/api/v1/users/me/active-organization",
            json=patch_data,
            headers=headers
        )
        
        print(f"PATCH status: {resp.status_code}")
        print(f"PATCH headers: {dict(resp.headers)}")
        print(f"PATCH response text: {resp.text}")
        
        if resp.status_code == 200:
            try:
                result = resp.json()
                print(f"\nParsed JSON response:")
                print(json.dumps(result, indent=2))
                
                if "access_token" in result:
                    print(f"\n✓ access_token found in response")
                    print(f"New token: {result['access_token'][:50]}...")
                else:
                    print(f"\n⚠️ access_token NOT found in response")
                    print(f"Available keys: {list(result.keys())}")
                    
            except Exception as e:
                print(f"JSON parse error: {e}")

if __name__ == "__main__":
    asyncio.run(test())