import os
import shutil
import tempfile
import json

def safe_read_jsonl(file_path, max_lines=None):
    '''Safely read JSONL files that may have filesystem issues on B200 nodes'''
    try:
        # Try direct reading first (works on H100)
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = []
            for i, line in enumerate(f):
                if max_lines and i >= max_lines:
                    break
                lines.append(json.loads(line.strip()))
            return lines
    except OSError as e:
        if e.errno == 22:  # Invalid argument - filesystem issue
            print(f'Direct read failed on B200 node, copying to temp file...')
            # Copy to temp file and read
            with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.jsonl') as tmp:
                shutil.copy2(file_path, tmp.name)
                try:
                    with open(tmp.name, 'r', encoding='utf-8') as f:
                        lines = []
                        for i, line in enumerate(f):
                            if max_lines and i >= max_lines:
                                break
                            lines.append(json.loads(line.strip()))
                        return lines
                finally:
                    os.unlink(tmp.name)
        else:
            raise

# Patch the load_questions_from_jsonl function
def patched_load_questions_from_jsonl(file_path):
    '''Patched version that works on both H100 and B200 nodes'''
    return safe_read_jsonl(file_path)
