import json
import base64

def analyze_har(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        har_data = json.load(f)

    for entry in har_data['log']['entries']:
        request = entry['request']
        # Check if it is the correct AMF request
        if 'play.ninjasage.id/amf' in request['url']:
            
            post_data = request.get('postData', {})
            text_data = post_data.get('text', '')
            
            # Look for loginUser
            if "loginUser" in text_data:
                print(f"\n--- Found Request with 'loginUser' ---")
                print(f"URL: {request['url']}")
                print(f"Method: {request['method']}")
                print(f"Text Snippet: {text_data[:200]}")
                
                # Try to decode if base64
                import base64
                try:
                    # Remove potential non-base64 chars if any? No, usually it's clean.
                    # But HAR might escape things.
                    decoded = base64.b64decode(text_data)
                    print("Decoded Base64 successfully.")
                    print(f"Decoded Hex Start: {decoded[:50].hex()}")
                    
                    # Check for AMF
                    if decoded.startswith(b'\x00\x03') or decoded.startswith(b'\x00\x00'):
                        print("It is an AMF packet!")
                        # Save it
                        with open("login_user_real.bin", "wb") as f:
                            f.write(decoded)
                        print("Saved to login_user_real.bin")
                    else:
                        print("Decoded data is NOT standard AMF.")
                        print(f"Decoded start: {decoded[:100]}")
                        
                except Exception as e:
                    print(f"Not Base64 or error: {e}")
                    # Try raw
                    print(f"Raw Hex Start: {text_data.encode('utf-8', errors='replace')[:50].hex()}")
                    
                    # Try to save the raw text data to a file for inspection
                    with open("login_user_raw.txt", "w", encoding="utf-8") as f:
                        f.write(text_data)
                    print("Saved raw text to login_user_raw.txt")
                
                # Response
                response = entry['response']
                content = response['content']
                print(f"Response Status: {response['status']}")
                
                resp_text = content.get('text', '')
                try:
                    resp_bytes = resp_text.encode('latin1')
                    print(f"Response Hex: {resp_bytes.hex()}")
                except:
                    print("Could not encode response text to latin1")
                
                return # Stop after finding the first one

analyze_har(r'd:\NEW\kingjoki\play.ninjasage.har')
