
import re

def extract_influencers(file_path, email_column_name):
    influencers = []
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
        # Read the file in chunks or line by line to handle potential large size if needed.
        # But for now, let's try reading the whole thing since it's only a few tens of MBs likely.
        content = f.read()
        
        # SQL dumps often have INSERT INTO `influencers` (...) VALUES (v1), (v2);
        # Some dumps have multiple INSERT statements.
        
        # Regex to find INSERT statements and their VALUES blocks
        # We need to find the column list and the values.
        # This matches INSERT INTO `influencers` (`col1`, `col2`, ...) VALUES
        insert_pattern = re.compile(r"INSERT INTO `influencers` \((.*?)\) VALUES\s*(.*?);", re.S)
        matches = insert_pattern.findall(content)
        
        for columns_str, values_block in matches:
            columns = [c.strip('` ') for c in columns_str.split(',')]
            
            # Identify indices for email, first name, last name
            email_idx = None
            first_name_idx = None
            last_name_idx = None
            
            for i, col in enumerate(columns):
                if col.lower() in ['email', 'emailaddress']:
                    email_idx = i
                if col.lower() in ['first_name', 'firstname']:
                    first_name_idx = i
                if col.lower() in ['last_name', 'lastname']:
                    last_name_idx = i
            
            # Extract individual rows from the values block.
            # Values are separated by ), (
            # This is tricky because strings can contain ), (
            # But in standard SQL dumps, strings are single-quoted and escaped.
            
            # Let's use a smarter way to split the values block.
            # We look for the start '(' and end ')' of each row.
            
            rows = []
            current_row = []
            in_string = False
            bracket_depth = 0
            start = 0
            
            i = 0
            while i < len(values_block):
                char = values_block[i]
                if char == "'" and (i == 0 or values_block[i-1] != "\\"):
                    in_string = not in_string
                
                if not in_string:
                    if char == '(':
                        if bracket_depth == 0:
                            start = i + 1
                        bracket_depth += 1
                    elif char == ')':
                        bracket_depth -= 1
                        if bracket_depth == 0:
                            rows.append(values_block[start:i])
                i += 1
            
            for row_str in rows:
                # Split the row into values
                # Again, respecting quotes
                row_values = []
                current_val = []
                in_string = False
                i = 0
                while i < len(row_str):
                    char = row_str[i]
                    if char == "'" and (i == 0 or row_str[i-1] != "\\"):
                        in_string = not in_string
                    
                    if not in_string and char == ',':
                        row_values.append("".join(current_val).strip())
                        current_val = []
                    else:
                        current_val.append(char)
                    i += 1
                row_values.append("".join(current_val).strip()) # Add last value
                
                # Sanitize values (remove quotes)
                sanitized_values = []
                for v in row_values:
                    if v.startswith("'") and v.endswith("'"):
                        sanitized_values.append(v[1:-1])
                    else:
                        sanitized_values.append(v)
                
                record = {}
                if email_idx is not None and email_idx < len(sanitized_values):
                    record['email'] = sanitized_values[email_idx]
                if first_name_idx is not None and first_name_idx < len(sanitized_values):
                    record['first_name'] = sanitized_values[first_name_idx]
                if last_name_idx is not None and last_name_idx < len(sanitized_values):
                    record['last_name'] = sanitized_values[last_name_idx]
                
                if record.get('email'):
                    influencers.append(record)
                    
    return influencers

old_influencers = extract_influencers('revu_db.sql', 'emailAddress')
new_influencers = extract_influencers('DB.sql', 'email')

print(f"Total old influencers found with email: {len(old_influencers)}")
print(f"Total new influencers found with email: {len(new_influencers)}")

old_map = {i['email']: i for i in old_influencers}
new_map = {i['email']: i for i in new_influencers}

missing_emails = set(old_map.keys()) - set(new_map.keys())

print(f"\nMissing {len(missing_emails)} influencers:")
for email in missing_emails:
    inf = old_map[email]
    print(f"- {inf.get('first_name', '')} {inf.get('last_name', '')} ({email})")
