#!/usr/bin/env python3
"""
Test script to verify ERPNext API authentication and endpoints
"""

import requests
import json
import os
import urllib3

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

ERPNEXT_URL = "https://portal.wrightchoicehs.com"

def test_with_token_auth():
    """Test authentication using API token"""
    print("=== Testing Token Authentication ===")
    
    api_key = os.getenv('ERPNEXT_API_KEY')
    api_secret = os.getenv('ERPNEXT_API_SECRET')
    
    if not api_key or not api_secret:
        print("❌ Environment variables ERPNEXT_API_KEY and ERPNEXT_API_SECRET not set")
        print("Please set these environment variables:")
        print("export ERPNEXT_API_KEY=your_api_key")
        print("export ERPNEXT_API_SECRET=your_api_secret")
        return False
    
    # Concatenate API key and secret with colon as per ERPNext docs
    token = f"{api_key}:{api_secret}"
    print(f"Using token format: token {api_key}:***")
    
    # Test basic auth endpoint
    try:
        response = requests.get(
            f"{ERPNEXT_URL}/api/method/frappe.auth.get_logged_user",
            headers={
                "Authorization": f"token {token}",
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            verify=False,
            timeout=10
        )
        
        print(f"Auth test response: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"✅ Token auth successful!")
            print(f"Logged in as: {data.get('message', 'Unknown user')}")
            return True
        else:
            print(f"❌ Token auth failed: {response.status_code}")
            print(f"Response: {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Token auth error: {str(e)}")
        return False

def test_with_password_auth():
    """Test authentication using username/password"""
    print("\n=== Testing Password Authentication ===")
    
    username = input("Enter username/email: ")
    password = input("Enter password: ")
    
    if not username or not password:
        print("❌ Username and password required")
        return False
    
    try:
        # Login request
        login_response = requests.post(
            f"{ERPNEXT_URL}/api/method/login",
            json={
                "usr": username,
                "pwd": password
            },
            headers={
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            verify=False,
            timeout=10
        )
        
        print(f"Login response: {login_response.status_code}")
        if login_response.status_code == 200:
            print("✅ Password login successful")
            
            # Test authenticated request with session
            session = requests.Session()
            session.cookies.update(login_response.cookies)
            
            test_response = session.get(
                f"{ERPNEXT_URL}/api/method/frappe.auth.get_logged_user",
                headers={"Accept": "application/json"},
                verify=False
            )
            
            if test_response.status_code == 200:
                print(f"✅ Session auth successful: {test_response.json()}")
                return True
            else:
                print(f"❌ Session auth failed: {test_response.text}")
                return False
        else:
            print(f"❌ Password login failed: {login_response.text}")
            return False
            
    except Exception as e:
        print(f"❌ Password auth error: {str(e)}")
        return False

def test_api_endpoints():
    """Test available API endpoints"""
    print("\n=== Testing API Endpoints ===")
    
    # Try to get list of doctypes
    api_key = os.getenv('ERPNEXT_API_KEY')
    api_secret = os.getenv('ERPNEXT_API_SECRET')
    
    if not api_key or not api_secret:
        print("❌ Need API credentials to test endpoints")
        return
    
    headers = {
        "Authorization": f"token {api_key}:{api_secret}",
        "Accept": "application/json"
    }
    
    # Test common endpoints
    endpoints_to_test = [
        "/api/resource/Contact",
        "/api/resource/Lead", 
        "/api/resource/Client Lead",
        "/api/method/frappe.desk.search.search_link"
    ]
    
    for endpoint in endpoints_to_test:
        try:
            response = requests.get(
                f"{ERPNEXT_URL}{endpoint}",
                headers=headers,
                verify=False,
                timeout=10
            )
            
            print(f"Endpoint {endpoint}: {response.status_code}")
            if response.status_code == 200:
                data = response.json()
                print(f"  ✅ Success - {len(data.get('data', []))} records")
            else:
                print(f"  ❌ Failed - {response.text[:100]}...")
                
        except Exception as e:
            print(f"  ❌ Error testing {endpoint}: {str(e)}")

def main():
    print("ERPNext API Authentication Test")
    print("=" * 40)
    
    # Test token authentication first
    token_success = test_with_token_auth()
    
    # If token auth fails, try password auth
    if not token_success:
        password_success = test_with_password_auth()
        if not password_success:
            print("\n❌ All authentication methods failed")
            return
    
    # Test API endpoints
    test_api_endpoints()
    
    print("\n" + "=" * 40)
    print("Test completed")

if __name__ == "__main__":
    main()