#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script to see how your file format is parsed
"""

import re

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 extract_credentials(line):
    """Extract email and password from line in various formats"""
    original_line = line
    # Remove URLs if present
    line = re.sub(r'https?://[^\s]+', '', line)
    line = line.strip()
    
    # Find email in line (always look for email pattern first)
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    email_match = re.search(email_pattern, line)
    
    if not email_match:
        return None, None, original_line
    
    email = email_match.group(0)
    
    # Try format: email:password (colon separator)
    if ':' in line:
        colon_parts = line.split(':')
        for i, part in enumerate(colon_parts):
            if email in part:
                if i + 1 < len(colon_parts):
                    password = ':'.join(colon_parts[i+1:]).strip()
                    if password and len(password) >= 3:
                        return email, password, original_line
                break
    
    # Try format: tab-separated or space-separated
    if '\t' in line:
        parts = line.split('\t')
    else:
        parts = line.split()
    
    # Find email index
    email_index = -1
    for i, part in enumerate(parts):
        if email in part:
            email_index = i
            break
    
    if email_index >= 0:
        # Try password after email
        if email_index + 1 < len(parts):
            password = parts[email_index + 1].strip()
            password = re.sub(r'^[|:\t]+|[|:\t]+$', '', password)
            if password and len(password) >= 3:
                return email, password, original_line
        
        # Try password before email
        if email_index > 0:
            password = parts[email_index - 1].strip()
            password = re.sub(r'^[|:\t]+|[|:\t]+$', '', password)
            if password and len(password) >= 3 and not is_valid_email(password):
                return email, password, original_line
        
        # Try to find password anywhere in line
        password = ''
        for part in parts:
            part = part.strip()
            if email in part or 'http' in part.lower() or '@' in part or is_valid_email(part):
                continue
            clean_part = re.sub(r'^[|:\t]+|[|:\t]+$', '', part)
            if len(clean_part) >= 3 and len(clean_part) <= 100 and len(clean_part) > len(password):
                password = clean_part
        
        if password:
            return email, password, original_line
    
    return email, None, original_line

# Test with sample file
INPUT_FILE = "app.pipedrive.com.txt"

print("=" * 80)
print("TESTING FILE PARSING")
print("=" * 80)
print(f"Reading from: {INPUT_FILE}\n")

try:
    with open(INPUT_FILE, 'r', encoding='utf-8', errors='ignore') as f:
        lines = f.readlines()
except FileNotFoundError:
    print(f"[!] File '{INPUT_FILE}' not found!")
    print(f"[!] Please create '{INPUT_FILE}' with your credentials")
    exit(1)

print(f"Total lines: {len(lines)}\n")
print("=" * 80)
print("PARSING RESULTS (First 10 lines):")
print("=" * 80)

for i, line in enumerate(lines[:10], 1):
    line = line.strip()
    if not line:
        continue
    
    email, password, original = extract_credentials(line)
    
    print(f"\nLine {i}:")
    print(f"  Original: {original[:100]}")
    if email:
        print(f"  ✓ Email found: {email}")
        if password:
            print(f"  ✓ Password found: {password[:30]}...")
            print(f"  ✓ STATUS: READY TO TEST")
        else:
            print(f"  ✗ Password: NOT FOUND")
            print(f"  ✗ STATUS: SKIP")
    else:
        print(f"  ✗ Email: NOT FOUND")
        print(f"  ✗ STATUS: SKIP")

print("\n" + "=" * 80)
print("SUMMARY:")
print("=" * 80)

total = len(lines)
parsed_email = 0
parsed_both = 0

for line in lines:
    if not line.strip():
        continue
    email, password, _ = extract_credentials(line.strip())
    if email:
        parsed_email += 1
        if password:
            parsed_both += 1

print(f"Total lines: {total}")
print(f"Lines with email: {parsed_email}")
print(f"Lines with email + password: {parsed_both}")
print(f"Ready to test: {parsed_both}")
print("=" * 80)

if parsed_both == 0:
    print("\n[!] WARNING: No credentials could be extracted!")
    print("[!] Please check the file format.")
else:
    print(f"\n[+] SUCCESS: {parsed_both} credentials ready to test!")

