#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test Pipedrive login with better method
"""

import requests
import json

LOGIN_URL = "https://app.pipedrive.com/auth/login"

# Test with one credential
email = "Enggmateen6@gmail.com"
password = "Pipedrive123.."

session = requests.Session()

# Better headers
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'en-US,en;q=0.9',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'https://app.pipedrive.com',
    'Referer': 'https://app.pipedrive.com/auth/login',
    'X-Requested-With': 'XMLHttpRequest',
}

print("Testing Pipedrive login...")
print(f"Email: {email}")

try:
    # Get login page first
    print("\n[1] Getting login page...")
    response = session.get(LOGIN_URL, headers=headers, timeout=10)
    print(f"    Status: {response.status_code}")
    
    # Try different login endpoints
    login_endpoints = [
        "https://app.pipedrive.com/auth/login",
        "https://app.pipedrive.com/api/v1/auth/login",
        "https://app.pipedrive.com/auth/api/login",
    ]
    
    login_data = {
        'email': email,
        'password': password,
        'remember_me': 'true'
    }
    
    for endpoint in login_endpoints:
        print(f"\n[2] Trying endpoint: {endpoint}")
        try:
            resp = session.post(endpoint, data=login_data, headers=headers, allow_redirects=True, timeout=10)
            print(f"    Status: {resp.status_code}")
            print(f"    Final URL: {resp.url[:80]}")
            
            if '/auth/login' not in resp.url:
                print(f"    ✓ SUCCESS! Redirected to: {resp.url}")
                break
        except Exception as e:
            print(f"    Error: {str(e)[:50]}")
    
    # Check cookies
    print(f"\n[3] Cookies: {len(session.cookies)} cookies")
    for cookie in session.cookies:
        print(f"    {cookie.name}: {cookie.value[:30]}...")
        
except Exception as e:
    print(f"Error: {str(e)}")
    import traceback
    traceback.print_exc()

