#!/usr/bin/env python3
"""
Decode the token to check scope_id.
"""

import json
import urllib.request
import urllib.parse
import base64

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

def decode_jwt(token):
    """Decode JWT token to get payload"""
    try:
        parts = token.split('.')
        if len(parts) == 3:
            payload = parts[1]
            # Add padding if needed
            padding = 4 - len(payload) % 4
            if padding != 4:
                payload += '=' * padding
            decoded = base64.b64decode(payload)
            return json.loads(decoded)
    except Exception as e:
        print(f"⚠️ Could not decode token: {e}")
    return {}

# 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"Initial token: {token[:30]}...")
        
        # Decode initial token
        initial_decoded = decode_jwt(token)
        print(f"Initial token payload:")
        for key, value in initial_decoded.items():
            print(f"  {key}: {value}")
        
        # Try switch with org_id
        payload = {"org_id": 21}
        print(f"\n🔄 Switching to org_id 21...")
        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'
            }
        )
        
        with urllib.request.urlopen(req) as resp:
            switch_response = json.loads(resp.read().decode('utf-8'))
            new_token = switch_response.get('access_token')
            
            if new_token:
                print(f"✅ New token received: {new_token[:30]}...")
                
                # Decode new token
                new_decoded = decode_jwt(new_token)
                print(f"New token payload:")
                for key, value in new_decoded.items():
                    print(f"  {key}: {value}")
                
                print(f"\n🔍 Comparison:")
                print(f"  Initial scope_id: {initial_decoded.get('scope_id')}")
                print(f"  New scope_id: {new_decoded.get('scope_id')}")
                
                if new_decoded.get('scope_id') != initial_decoded.get('scope_id'):
                    print("✅ Scope ID changed in token!")
                else:
                    print("⚠️ Scope ID unchanged in token")
            else:
                print("❌ No new token in response")
                
except Exception as e:
    print(f"Error: {e}")