#!/usr/bin/env python3
"""Find function names from added_functs.txt in new_tests.txt and show matching lines."""
import sys
import re

def read_function_names(filename):
    """Read function names from file, one per line."""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.", file=sys.stderr)
        sys.exit(1)

def read_test_file(filename):
    """Read test file content."""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.readlines()
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.", file=sys.stderr)
        sys.exit(1)

def find_matching_lines(function_name, test_lines):
    """Find lines in test_lines that contain function_name."""
    matches = []
    # Create pattern to match function name in various contexts:
    # - cuda.functionName
    # - cudart.functionName
    # - supportsCudaAPI("functionName")
    # - functionName in docstrings/comments
    pattern = re.compile(re.escape(function_name), re.IGNORECASE)
    
    for line_num, line in enumerate(test_lines, start=1):
        if pattern.search(line):
            matches.append((line_num, line.rstrip()))
    
    return matches

def main():
    added_functs_file = '/home/rgrossekunst/added_functs.txt'
    new_tests_file = '/home/rgrossekunst/new_tests.txt'
    
    # Read function names
    function_names = read_function_names(added_functs_file)
    
    # Read test file
    test_lines = read_test_file(new_tests_file)
    
    # Track functions with no matches
    no_matches = []
    
    # Process each function name
    for func_name in function_names:
        matches = find_matching_lines(func_name, test_lines)
        
        if matches:
            print(f"\n{'='*80}")
            print(f"Function: {func_name}")
            print(f"{'='*80}")
            print(f"Found {len(matches)} matching line(s):\n")
            for line_num, line in matches:
                print(f"  Line {line_num:4d}: {line}")
        else:
            no_matches.append(func_name)
    
    # Report functions with no matches
    if no_matches:
        print(f"\n{'='*80}")
        print("ATTENTION: Functions with NO matches found:")
        print(f"{'='*80}")
        for func_name in no_matches:
            print(f"  ⚠️  {func_name}")
        print(f"\nTotal: {len(no_matches)} function(s) without matches")
    else:
        print(f"\n{'='*80}")
        print("✓ All functions have matches!")
        print(f"{'='*80}")
    
    print(f"\nSummary:")
    print(f"  Total functions checked: {len(function_names)}")
    print(f"  Functions with matches: {len(function_names) - len(no_matches)}")
    print(f"  Functions without matches: {len(no_matches)}")

if __name__ == '__main__':
    main()
