#!/usr/bin/env python3
"""
Check the full response from organization switch.
"""

import json
import urllib.request
import urllib.parse

API_BASE = "http://sf_api:8000/api/v1"
EMAIL = "tester_pro@profibot.hu"
PASSWORD = "Password123!"

# Login
print("Logging in...")
data = urllib.parse.urlencode({
    'username': EMAIL,
    'password': PASSWORD
}).encode('utf-8')

req = urllib.request.Request(f"{API_BASE}/auth/login", data=data, method='POST')
req.add_header('Content-Type', 'application/x-www-form-urlencoded')

try:
    with urllib.request.urlopen(req) as response:
        response_data = json.loads(response.read().decode('utf-8'))
        token = response_data.get('access_token')
        print(f"Token: {token[:30]}...")
        
        # Try switch with org_id
        payload = {"org_id": 21}
        print(f"\nTrying switch with payload: {payload}")
        data = json.dumps(payload).encode('utf-8')
        req = urllib.request.Request(
            f"{API_BASE}/users/me/active-organization",
            data=data,
            method='PATCH',
            headers={
                'Authorization': f'Bearer {token}',
                'Content-Type': 'application/json'
            }
        )
        
        try:
            with urllib.request.urlopen(req) as resp:
                print(f"Success! Status: {resp.status}")
                full_response = resp.read().decode('utf-8')
                print(f"Full response ({len(full_response)} chars):")
                print(full_response)
                
                # Parse and check structure
                parsed = json.loads(full_response)
                print(f"\nResponse keys: {list(parsed.keys())}")
                if 'access_token' in parsed:
                    print(f"✅ access_token found: {parsed['access_token'][:30]}...")
                else:
                    print("❌ No access_token in response")
                    
                if 'user' in parsed:
                    print(f"✅ user found in response")
                else:
                    print("❌ No user in response")
                    
        except urllib.error.HTTPError as e:
            print(f"HTTP Error {e.code}: {e.reason}")
            print(f"Response: {e.read().decode('utf-8')}")
        except Exception as e:
            print(f"Error: {e}")
                
except Exception as e:
    print(f"Login error: {e}")