#!/usr/bin/env python3
"""
Script to remove chi::Task::Copy() calls from task Copy() methods

This script finds and removes lines containing chi::Task::Copy(other.template Cast<chi::Task>())
from Copy() methods in task definition files. The base Task copy is now handled automatically
by the NewCopy autogenerated code.

Usage:
    python3 remove_task_copy_calls.py <directory>
"""

import re
import sys
from pathlib import Path

def process_file(file_path):
    """
    Process a single file to remove chi::Task::Copy calls from Copy methods

    Returns True if file was modified, False otherwise
    """
    with open(file_path, 'r') as f:
        content = f.read()

    original_content = content

    # Pattern to match chi::Task::Copy line and potential surrounding whitespace
    # Matches variations like:
    #   chi::Task::Copy(other.template Cast<chi::Task>());
    #   chi::Task::Copy(other.Cast<chi::Task>());
    #   // Copy base task fields
    #   chi::Task::Copy(other.template Cast<chi::Task>());

    # Pattern 1: Match the exact line with potential comment before it
    pattern1 = r'[ \t]*//[^\n]*Copy base[^\n]*\n[ \t]*chi::Task::Copy\([^)]+\);[ \t]*\n'
    content = re.sub(pattern1, '', content)

    # Pattern 2: Match standalone chi::Task::Copy line
    pattern2 = r'[ \t]*chi::Task::Copy\([^)]+\.template Cast<chi::Task>\(\)\);[ \t]*\n'
    content = re.sub(pattern2, '', content)

    # Pattern 3: Match without .template
    pattern3 = r'[ \t]*chi::Task::Copy\([^)]+\.Cast<chi::Task>\(\)\);[ \t]*\n'
    content = re.sub(pattern3, '', content)

    # Pattern 4: Clean up extra blank lines that might result
    # Replace 3+ consecutive newlines with just 2
    content = re.sub(r'\n\n\n+', '\n\n', content)

    if content != original_content:
        with open(file_path, 'w') as f:
            f.write(content)
        return True

    return False

def find_task_files(directory):
    """
    Find all task definition files (files ending with _tasks.h)
    """
    directory = Path(directory)
    return list(directory.rglob('*_tasks.h'))

def main():
    if len(sys.argv) != 2:
        print("Usage: python3 remove_task_copy_calls.py <directory>")
        print("\nExample:")
        print("  python3 remove_task_copy_calls.py /home/llogan/Documents/Projects/iowarp/iowarp-runtime")
        sys.exit(1)

    directory = sys.argv[1]

    print(f"Searching for task files in: {directory}")
    task_files = find_task_files(directory)

    if not task_files:
        print("No task files found!")
        return

    print(f"\nFound {len(task_files)} task files")

    modified_count = 0
    for file_path in task_files:
        print(f"\nProcessing: {file_path}")
        if process_file(file_path):
            modified_count += 1
            print(f"  ✓ Modified")
        else:
            print(f"  - No changes needed")

    print(f"\n{'='*60}")
    print(f"Summary: Modified {modified_count} out of {len(task_files)} files")
    print(f"{'='*60}")

    if modified_count > 0:
        print("\nFiles have been updated to remove chi::Task::Copy() calls.")
        print("The base Task copy is now handled automatically by autogenerated NewCopy code.")
        print("\nNext steps:")
        print("  1. Review the changes with: git diff")
        print("  2. Rebuild chi_refresh_repo: make chi_refresh_repo")
        print("  3. Regenerate autogen files: ./build/bin/chi_refresh_repo chimods")
        print("  4. Rebuild the project: make")

if __name__ == '__main__':
    main()
