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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
"""
Data processing utilities for Ruby method datasets.

This module provides functions to load, preprocess, and prepare Ruby method
data for GNN training. Includes custom Dataset class for AST to graph conversion.
"""

import json
import random
import os
import logging
from pathlib import Path
from typing import List, Dict, Any, Tuple, Optional, Union
try:
    import torch
    from torch_geometric.data import Data
    TORCH_AVAILABLE = True
except ImportError:
    TORCH_AVAILABLE = False


def load_methods_json(filepath: str) -> List[Dict[str, Any]]:
    """
    Load Ruby methods from JSON file.
    
    Args:
        filepath: Path to the JSON file containing method data
        
    Returns:
        List of method dictionaries
    """
    with open(filepath, 'r') as f:
        return json.load(f)


def methods_to_dataframe(methods: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """
    Convert list of method dictionaries to a structured format.
    
    Args:
        methods: List of method dictionaries
        
    Returns:
        List of method dictionaries (pass-through for compatibility)
    """
    return methods


def filter_methods_by_length(methods: List[Dict[str, Any]], min_lines: int = 5, max_lines: int = 100) -> List[Dict[str, Any]]:
    """
    Filter methods by source code length.
    
    Args:
        methods: List of method dictionaries
        min_lines: Minimum number of lines
        max_lines: Maximum number of lines
        
    Returns:
        Filtered list of methods
    """
    filtered = []
    for method in methods:
        if 'raw_source' in method:
            line_count = len(method['raw_source'].split('\n'))
            if min_lines <= line_count <= max_lines:
                method['line_count'] = line_count
                filtered.append(method)
    return filtered
    """
    Filter methods by source code length.
    
    Args:
        df: DataFrame containing method data
        min_lines: Minimum number of lines
        max_lines: Maximum number of lines
        
    Returns:
        Filtered DataFrame
    """
    df['line_count'] = df['raw_source'].apply(lambda x: len(x.split('\n')))
    return df[(df['line_count'] >= min_lines) & (df['line_count'] <= max_lines)]


class ASTNodeEncoder:
    """
    Encoder for mapping AST node types to feature vectors.
    
    This class maintains a vocabulary of AST node types found in Ruby code
    and maps them to dense feature vectors for GNN processing.
    """
    
    def __init__(self):
        """Initialize the node encoder with common Ruby AST node types."""
        # Common Ruby AST node types based on the parser gem
        self.node_types = [
            'def', 'defs', 'args', 'arg', 'begin', 'end', 'lvasgn', 'ivasgn', 'gvasgn',
            'cvasgn', 'send', 'block', 'if', 'unless', 'while', 'until', 'for', 'case',
            'when', 'rescue', 'ensure', 'retry', 'break', 'next', 'redo', 'return',
            'yield', 'super', 'zsuper', 'lambda', 'proc', 'and', 'or', 'not', 'true',
            'false', 'nil', 'self', 'int', 'float', 'str', 'sym', 'regexp', 'array',
            'hash', 'pair', 'splat', 'kwsplat', 'block_pass', 'const', 'cbase',
            'lvar', 'ivar', 'gvar', 'cvar', 'casgn', 'masgn', 'mlhs', 'op_asgn',
            'and_asgn', 'or_asgn', 'back_ref', 'nth_ref', 'class', 'sclass', 'module',
            'defined?', 'alias', 'undef', 'range', 'irange', 'erange', 'regopt'
        ]
        
        # Create mapping from node type to index
        self.type_to_idx = {node_type: idx for idx, node_type in enumerate(self.node_types)}
        self.unknown_idx = len(self.node_types)  # Index for unknown node types
        self.vocab_size = len(self.node_types) + 1  # +1 for unknown
        
    def encode_node_type(self, node_type: str) -> int:
        """
        Encode a node type to its integer index.
        
        Args:
            node_type: The AST node type string
            
        Returns:
            Integer index for the node type
        """
        return self.type_to_idx.get(node_type, self.unknown_idx)
    
    def create_node_features(self, node_type: str) -> List[float]:
        """
        Create feature vector for a node type.
        
        Args:
            node_type: The AST node type string
            
        Returns:
            Feature vector as list of floats
        """
        # Simple one-hot encoding for now
        features = [0.0] * self.vocab_size
        idx = self.encode_node_type(node_type)
        features[idx] = 1.0
        return features


class ASTGraphConverter:
    """
    Converter for transforming AST JSON to graph representation.
    
    This class parses the AST JSON structure and converts it into
    a graph format suitable for GNN processing.
    """
    
    def __init__(self):
        """Initialize the AST to graph converter."""
        self.node_encoder = ASTNodeEncoder()
        self.reset()
    
    def reset(self):
        """Reset the converter state for processing a new AST."""
        self.nodes = []  # List of node features
        self.edges = []  # List of edge tuples (parent_idx, child_idx)
        self.edge_attrs = []  # List of edge attributes [child_index, depth, num_siblings]
        self.node_depths = []  # Depth of each node in the tree
        self.node_child_indices = []  # Position of each node among its siblings
        self.node_count = 0
    
    def parse_ast_json(self, ast_json: str) -> Dict[str, Any]:
        """
        Parse AST JSON string and convert to graph representation.
        
        Args:
            ast_json: JSON string representing the AST
            
        Returns:
            Dictionary containing node features, edge indices, and edge attributes.
            edge_attr contains [child_index, depth, num_siblings] per edge.
            node_pos contains [child_index, depth] per node for positional encoding.
        """
        self.reset()
        
        try:
            ast_data = json.loads(ast_json)
            self._process_node(ast_data, parent_idx=None, depth=0, child_index=0, num_siblings=1)
            
            # Convert to appropriate format
            if not self.nodes:
                # Handle empty AST case
                node_features = [[0.0] * self.node_encoder.vocab_size]
                edge_index = [[], []]  # Empty edge list
                edge_attr = []
                node_pos = [[0, 0]]
            else:
                node_features = self.nodes
                if self.edges:
                    # Transpose edge list to [2, num_edges] format
                    edge_index = [[], []]
                    for parent, child in self.edges:
                        edge_index[0].append(parent)
                        edge_index[1].append(child)
                else:
                    edge_index = [[], []]
                edge_attr = self.edge_attrs
                node_pos = list(zip(self.node_child_indices, self.node_depths))
            
            return {
                'x': node_features,
                'edge_index': edge_index,
                'edge_attr': edge_attr,
                'node_pos': node_pos,
                'num_nodes': len(self.nodes) if self.nodes else 1
            }
            
        except (json.JSONDecodeError, Exception):
            # Handle malformed JSON or other errors gracefully
            return {
                'x': [[0.0] * self.node_encoder.vocab_size],
                'edge_index': [[], []],
                'edge_attr': [],
                'node_pos': [[0, 0]],
                'num_nodes': 1
            }
    
    def _process_node(self, node: Union[Dict, List, str, int, float, None],
                      parent_idx: Optional[int] = None, depth: int = 0,
                      child_index: int = 0, num_siblings: int = 1) -> int:
        """
        Recursively process an AST node and its children.
        
        Args:
            node: The AST node (dict, list, or primitive)
            parent_idx: Index of the parent node
            depth: Depth of the current node in the AST
            child_index: Position of this node among its siblings (0-based)
            num_siblings: Total number of siblings (including this node)
            
        Returns:
            Index of the current node
        """
        if isinstance(node, dict) and 'type' in node:
            # This is an AST node with a type
            node_type = node['type']
            current_idx = self.node_count
            self.node_count += 1
            
            # Create node features
            features = self.node_encoder.create_node_features(node_type)
            self.nodes.append(features)
            self.node_depths.append(depth)
            self.node_child_indices.append(child_index)
            
            # Add edge from parent to current node
            if parent_idx is not None:
                self.edges.append((parent_idx, current_idx))
                self.edge_attrs.append([child_index, depth, num_siblings])
            
            # Process children with positional information
            if 'children' in node:
                children = node['children']
                n_children = len(children)
                for i, child in enumerate(children):
                    self._process_node(child, current_idx, depth=depth + 1,
                                       child_index=i, num_siblings=n_children)
            
            return current_idx
            
        elif isinstance(node, list):
            # Process list of nodes
            n_items = len(node)
            for i, child in enumerate(node):
                self._process_node(child, parent_idx, depth=depth,
                                   child_index=i, num_siblings=n_items)
            return parent_idx if parent_idx is not None else -1
            
        else:
            # Leaf node (string, int, float, None)
            if parent_idx is not None:
                current_idx = self.node_count
                self.node_count += 1
                
                # Create a generic leaf node
                leaf_type = 'leaf_' + type(node).__name__
                features = self.node_encoder.create_node_features(leaf_type)
                self.nodes.append(features)
                self.node_depths.append(depth)
                self.node_child_indices.append(child_index)
                
                # Add edge from parent to leaf
                self.edges.append((parent_idx, current_idx))
                self.edge_attrs.append([child_index, depth, num_siblings])
                
                return current_idx
            return -1


def load_jsonl_file(filepath: str, limit: Optional[int] = None) -> List[Dict[str, Any]]:
    """
    Load data from a JSONL file.
    
    Args:
        filepath: Path to the JSONL file
        limit: Optional maximum number of lines to load.
        
    Returns:
        List of dictionaries from the JSONL file
    """
    data = []
    with open(filepath, 'r', encoding='utf-8') as f:
        for i, line in enumerate(f):
            if limit is not None and i >= limit:
                break
            line = line.strip()
            if line:
                try:
                    data.append(json.loads(line))
                except json.JSONDecodeError:
                    continue  # Skip malformed lines
    return data


class RubyASTDataset:
    """
    Dataset class for loading Ruby AST data and converting to graph format.
    
    This class loads JSONL files containing Ruby method data and converts
    the AST representations to graph objects suitable for GNN training.
    """
    
    def __init__(self, jsonl_path: str, transform=None, limit: Optional[int] = None):
        """
        Initialize the dataset.
        
        Args:
            jsonl_path: Path to the JSONL file containing method data
            transform: Optional transform to apply to each sample
            limit: Optional maximum number of samples to load.
        """
        self.jsonl_path = jsonl_path
        self.transform = transform
        self.converter = ASTGraphConverter()
        
        # Load the data
        self.data = load_jsonl_file(jsonl_path, limit=limit)
        
        print(f"Loaded {len(self.data)} samples from {jsonl_path}")
    
    def __len__(self) -> int:
        """Return the number of samples in the dataset."""
        return len(self.data)
    
    def __getitem__(self, idx: int) -> Dict[str, Any]:
        """
        Get a sample from the dataset.
        
        Args:
            idx: Index of the sample
            
        Returns:
            Dictionary containing graph data and target
        """
        if idx < 0 or idx >= len(self.data):
            raise IndexError(f"Index {idx} out of range for dataset of size {len(self.data)}")
        
        sample = self.data[idx]
        
        # Convert AST to graph
        graph_data = self.converter.parse_ast_json(sample['ast_json'])
        
        # Create the data object
        result = {
            'x': graph_data['x'],
            'edge_index': graph_data['edge_index'],
            'y': [sample.get('complexity_score', 5.0)],  # Default complexity score if missing
            'num_nodes': graph_data['num_nodes'],
            'id': sample.get('id', f'sample_{idx}'),
            'repo_name': sample.get('repo_name', ''),
            'file_path': sample.get('file_path', '')
        }
        
        # Apply transform if provided
        if self.transform:
            result = self.transform(result)
        
        return result
    
    def get_feature_dim(self) -> int:
        """Return the dimension of node features."""
        return self.converter.node_encoder.vocab_size


def collate_graphs(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Collate function for batching graph data.
    
    Args:
        batch: List of graph data dictionaries
        
    Returns:
        Batched graph data
    """
    if not batch:
        raise ValueError("Cannot collate empty batch")
    
    # Collect all node features and edge indices
    all_x = []
    all_edge_index = [[], []]  # [source_nodes, target_nodes]
    all_y = []
    batch_idx = []
    node_offset = 0
    
    metadata = {
        'ids': [],
        'repo_names': [],
        'file_paths': []
    }
    
    for i, sample in enumerate(batch):
        # Node features
        all_x.extend(sample['x'])
        
        # Edge indices (offset by current node count)
        edges = sample['edge_index']
        if len(edges[0]) > 0:  # Only offset if there are edges
            for j in range(len(edges[0])):
                all_edge_index[0].append(edges[0][j] + node_offset)
                all_edge_index[1].append(edges[1][j] + node_offset)
        
        # Target values
        all_y.extend(sample['y'])
        
        # Batch indices for each node
        num_nodes = sample['num_nodes']
        batch_idx.extend([i] * num_nodes)
        node_offset += num_nodes
        
        # Metadata
        metadata['ids'].append(sample['id'])
        metadata['repo_names'].append(sample['repo_name'])
        metadata['file_paths'].append(sample['file_path'])
    
    return {
        'x': all_x,
        'edge_index': all_edge_index,
        'y': all_y,
        'batch': batch_idx,
        'num_graphs': len(batch),
        'metadata': metadata
    }


class SimpleDataLoader:
    """
    Simple DataLoader implementation for batching data.
    
    This provides a basic implementation that can be used when PyTorch
    DataLoader is not available, and can easily be replaced with the real
    PyTorch DataLoader when dependencies are installed.
    """
    
    def __init__(self, dataset, batch_size: int = 1, shuffle: bool = False, collate_fn=None):
        """
        Initialize the DataLoader.
        
        Args:
            dataset: Dataset to load from
            batch_size: Number of samples per batch
            shuffle: Whether to shuffle the data
            collate_fn: Function to collate samples into batches
        """
        self.dataset = dataset
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.collate_fn = collate_fn or collate_graphs
        
        # Create indices
        self.indices = list(range(len(dataset)))
        if shuffle:
            import random
            random.shuffle(self.indices)
    
    def __len__(self) -> int:
        """Return number of batches."""
        return (len(self.dataset) + self.batch_size - 1) // self.batch_size
    
    def __iter__(self):
        """Iterate over batches."""
        for i in range(0, len(self.dataset), self.batch_size):
            batch_indices = self.indices[i:i + self.batch_size]
            batch = [self.dataset[idx] for idx in batch_indices]
            yield self.collate_fn(batch)


class PairedDataset:
    """
    Dataset class for loading paired Ruby AST and text description data.
    
    This class loads the paired_data.jsonl file containing Ruby method data 
    and converts AST representations to graph objects paired with text descriptions.
    For each method, it randomly samples one description from the available descriptions.
    """
    
    def __init__(self, jsonl_path: str, transform=None, seed: Optional[int] = None, limit: Optional[int] = None):
        """
        Initialize the paired dataset.
        
        Args:
            jsonl_path: Path to the paired_data.jsonl file
            transform: Optional transform to apply to each sample
            seed: Random seed for consistent description sampling
            limit: Optional maximum number of samples to load.
        """
        self.jsonl_path = jsonl_path
        self.transform = transform
        self.converter = ASTGraphConverter()
        
        if seed is not None:
            random.seed(seed)
        
        # Load the data
        self.data = load_jsonl_file(jsonl_path, limit=limit)
        
        print(f"Loaded {len(self.data)} samples from {jsonl_path}")
    
    def __len__(self) -> int:
        """Return the number of samples in the dataset."""
        return len(self.data)
    
    def __getitem__(self, idx: int) -> Tuple[Dict[str, Any], str]:
        """
        Get a sample from the dataset.
        
        Args:
            idx: Index of the sample
            
        Returns:
            Tuple of (graph_data, text_description)
        """
        if idx < 0 or idx >= len(self.data):
            raise IndexError(f"Index {idx} out of range for dataset of size {len(self.data)}")
        
        sample = self.data[idx]
        
        # Convert AST to graph
        graph_data = self.converter.parse_ast_json(sample['ast_json'])
        
        # Randomly sample one description
        descriptions = sample.get('descriptions', [])
        if descriptions:
            description = random.choice(descriptions)
            text_description = description['text']
        else:
            # Fallback to method name if no descriptions available
            text_description = sample.get('method_name', 'unknown_method')
        
        # Create the graph data object
        graph_result = {
            'x': graph_data['x'],
            'edge_index': graph_data['edge_index'],
            'num_nodes': graph_data['num_nodes'],
            'id': sample.get('id', f'sample_{idx}'),
            'repo_name': sample.get('repo_name', ''),
            'file_path': sample.get('file_path', '')
        }
        
        # Apply transform if provided
        if self.transform:
            graph_result = self.transform(graph_result)
        
        return graph_result, text_description
    
    def get_feature_dim(self) -> int:
        """Return the dimension of node features."""
        return self.converter.node_encoder.vocab_size


def collate_paired_data(batch: List[Tuple[Dict[str, Any], str]]) -> Tuple[Dict[str, Any], List[str]]:
    """
    Collate function for batching paired graph and text data.
    
    Args:
        batch: List of (graph_data, text_description) tuples
        
    Returns:
        Tuple of (batched_graph_data, list_of_text_descriptions)
    """
    if not batch:
        raise ValueError("Cannot collate empty batch")
    
    # Separate graph data and text descriptions
    graph_batch = [item[0] for item in batch]
    text_batch = [item[1] for item in batch]
    
    # Collate graph data manually (similar to collate_graphs but without 'y' field)
    all_x = []
    all_edge_index = [[], []]  # [source_nodes, target_nodes]
    batch_idx = []
    node_offset = 0
    
    metadata = {
        'ids': [],
        'repo_names': [],
        'file_paths': []
    }
    
    for i, sample in enumerate(graph_batch):
        # Node features
        all_x.extend(sample['x'])
        
        # Edge indices (offset by current node count)
        edges = sample['edge_index']
        if len(edges[0]) > 0:  # Only offset if there are edges
            for j in range(len(edges[0])):
                all_edge_index[0].append(edges[0][j] + node_offset)
                all_edge_index[1].append(edges[1][j] + node_offset)
        
        # Batch indices for each node
        num_nodes = sample['num_nodes']
        batch_idx.extend([i] * num_nodes)
        node_offset += num_nodes
        
        # Metadata
        metadata['ids'].append(sample['id'])
        metadata['repo_names'].append(sample['repo_name'])
        metadata['file_paths'].append(sample['file_path'])
    
    batched_graphs = {
        'x': all_x,
        'edge_index': all_edge_index,
        'batch': batch_idx,
        'num_graphs': len(batch),
        'metadata': metadata
    }
    
    return batched_graphs, text_batch


class PairedDataLoader:
    """
    DataLoader for paired graph and text data.
    
    Extends SimpleDataLoader to handle paired (graph, text) data.
    """
    
    def __init__(self, dataset, batch_size: int = 1, shuffle: bool = False):
        """
        Initialize the PairedDataLoader.
        
        Args:
            dataset: PairedDataset to load from
            batch_size: Number of samples per batch
            shuffle: Whether to shuffle the data
        """
        self.dataset = dataset
        self.batch_size = batch_size
        self.shuffle = shuffle
        
        # Create indices
        self.indices = list(range(len(dataset)))
        if shuffle:
            random.shuffle(self.indices)
    
    def __len__(self) -> int:
        """Return number of batches."""
        return (len(self.dataset) + self.batch_size - 1) // self.batch_size
    
    def __iter__(self):
        """Iterate over batches."""
        for i in range(0, len(self.dataset), self.batch_size):
            batch_indices = self.indices[i:i + self.batch_size]
            batch = [self.dataset[idx] for idx in batch_indices]
            yield collate_paired_data(batch)



class PrecomputedRubyASTDataset:
    """
    Dataset class for loading precomputed Ruby AST graph data.

    This class can load .pt files containing pre-converted PyTorch Geometric
    Data objects for speed, but also supports processing .jsonl files as a fallback.
    """

    def __init__(self, path: str, transform=None):
        """
        Initialize the dataset.

        Args:
            path: Path to the .pt or .jsonl file containing graph data.
            transform: Optional transform to apply to each sample.
        """
        self.path = path
        self.transform = transform

        if not TORCH_AVAILABLE:
            raise ImportError("PyTorch and PyG are required for this dataset.")

        if path.endswith('.pt'):
            # Load the precomputed data into RAM
            self.data = torch.load(path, weights_only=False)
            print(f"Loaded {len(self.data)} precomputed graphs from {path}")
        elif path.endswith('.jsonl'):
            print(f"Processing JSONL file into graphs: {path}")
            jsonl_data = load_jsonl_file(path)
            converter = ASTGraphConverter()
            self.data = []
            for sample in jsonl_data:
                graph_data = converter.parse_ast_json(sample['ast_json'])

                x = torch.tensor(graph_data['x'], dtype=torch.float)
                edge_index = torch.tensor(graph_data['edge_index'], dtype=torch.long)
                y = torch.tensor([sample.get('complexity_score', 5.0)], dtype=torch.float)

                data_obj = Data(x=x, edge_index=edge_index, y=y)

                # Add positional attributes — always set so PyG collation is consistent
                ea = graph_data.get('edge_attr', [])
                data_obj.edge_attr = torch.tensor(
                    ea if ea else [], dtype=torch.float,
                ).reshape(-1, 3) if ea else torch.zeros((0, 3), dtype=torch.float)

                np_ = graph_data.get('node_pos', [])
                data_obj.node_pos = torch.tensor(
                    np_ if np_ else [[0, 0]], dtype=torch.float,
                )

                self.data.append(data_obj)
            print(f"Converted {len(self.data)} graphs from {path}")
        else:
            raise ValueError(f"Unsupported file type: {path}. Please provide a .pt or .jsonl file.")
    
    def __len__(self) -> int:
        """Return the number of samples in the dataset."""
        return len(self.data)
    
    def __getitem__(self, idx: int):
        """
        Get a sample from the dataset.
        
        Args:
            idx: Index of the sample
            
        Returns:
            PyTorch Geometric Data object
        """
        if idx < 0 or idx >= len(self.data):
            raise IndexError(f"Index {idx} out of range for dataset of size {len(self.data)}")
        
        sample = self.data[idx]
        
        if self.transform:
            sample = self.transform(sample)
            
        return sample


class PreCollatedDataset:
    """
    Dataset class for loading pre-collated batches of graph data.
    
    This class loads a .pt file where each item is an already-collated
    `torch_geometric.data.Batch` object. This is the most efficient
    way to load data as it eliminates all real-time collation overhead.
    """
    def __init__(self, pt_path: str):
        """
        Initialize the dataset.
        
        Args:
            pt_path: Path to the .pt file containing pre-collated batches.
        """
        # Load the list of pre-collated batches into RAM
        self.batches = torch.load(pt_path, weights_only=False)
        print(f"Loaded {len(self.batches)} pre-collated batches from {pt_path}")

    def __len__(self):
        return len(self.batches)

    def __getitem__(self, idx):
        return self.batches[idx]


def create_data_loaders(train_path: str, val_path: str, batch_size: int = 32, shuffle: bool = True, num_workers: Optional[int] = None, pre_collated: bool = False):
    """
    Create train and validation data loaders.
    
    Supports two modes:
    1. Standard loading from a dataset of individual graphs (`pre_collated=False`).
       This uses a PyG DataLoader to perform real-time batching.
    2. Pre-collated loading from a dataset of pre-batched graphs (`pre_collated=True`).
       This is the most performant option, as it has near-zero CPU overhead.

    Args:
        train_path: Path to training .pt file.
        val_path: Path to validation .pt file.
        batch_size: Batch size (used only if `pre_collated=False`).
        shuffle: Whether to shuffle training data.
        num_workers: Number of workers for data loading (used only if `pre_collated=False`).
        pre_collated: Whether the dataset files contain pre-collated batches.
        
    Returns:
        Tuple of (train_loader, val_loader)
    """
    if not TORCH_AVAILABLE:
        raise ImportError("PyTorch is required to create data loaders.")

    if pre_collated:
        # --- Pre-collated path (most efficient) ---
        train_dataset = PreCollatedDataset(train_path)
        val_dataset = PreCollatedDataset(val_path)
        
        # The collate_fn simply returns the already-collated batch.
        # The input `batch` is a list of size 1 containing our pre-made Batch object.
        collate_fn = lambda x: x[0]
        
        # DataLoader is just a simple iterator here, no real collation work.
        # num_workers > 0 can actually be slower due to overhead of sending
        # already-large batches between processes.
        from torch.utils.data import DataLoader
        train_loader = DataLoader(train_dataset, batch_size=1, shuffle=shuffle, num_workers=0, collate_fn=collate_fn)
        val_loader = DataLoader(val_dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_fn)
        
        print("✅ Using pre-collated data loader (maximum performance).")

    else:
        # --- Standard real-time collation path ---
        from torch_geometric.loader import DataLoader
        train_dataset = PrecomputedRubyASTDataset(train_path)
        val_dataset = PrecomputedRubyASTDataset(val_path)

        if num_workers is None:
            num_workers = os.cpu_count()

        train_loader = DataLoader(
            train_dataset, 
            batch_size=batch_size, 
            shuffle=shuffle,
            num_workers=num_workers,
            pin_memory=torch.cuda.is_available(),
            persistent_workers=num_workers > 0
        )
        val_loader = DataLoader(
            val_dataset, 
            batch_size=batch_size, 
            shuffle=False,
            num_workers=num_workers,
            pin_memory=torch.cuda.is_available(),
            persistent_workers=num_workers > 0
        )
        
        print(f"✅ Using standard PyG DataLoader with {num_workers} workers.")
    
    return train_loader, val_loader



def create_paired_data_loaders(paired_data_path: str, batch_size: int = 32, shuffle: bool = True, seed: Optional[int] = None):
    """
    Create data loader for paired graph and text data.
    
    Args:
        paired_data_path: Path to paired_data.jsonl file
        batch_size: Batch size for the loader
        shuffle: Whether to shuffle the data
        seed: Random seed for consistent description sampling
        
    Returns:
        PairedDataLoader instance
    """
    dataset = PairedDataset(paired_data_path, seed=seed)
    loader = PairedDataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
    
    return loader


class AutoregressiveASTDataset:
    """
    Dataset class for autoregressive AST generation training.
    
    This class loads paired Ruby AST and text description data and converts
    each AST into a sequence of (partial_graph, target_node) pairs for 
    autoregressive training. Each method generates multiple training examples.
    """
    
    def __init__(self, paired_data_path: str, max_sequence_length: int = 50, seed: Optional[int] = None,
                 precomputed_embeddings_path: Optional[str] = None):
        """
        Initialize the autoregressive dataset.
        
        Args:
            paired_data_path: Path to the paired_data.jsonl file
            max_sequence_length: Maximum number of nodes per sequence
            seed: Random seed for consistent description sampling
            precomputed_embeddings_path: Path to pre-computed text embeddings file (optional)
        """
        self.paired_data_path = paired_data_path
        self.max_sequence_length = max_sequence_length
        self.converter = ASTGraphConverter()
        
        if seed is not None:
            random.seed(seed)
        
        # Load pre-computed embeddings if available
        self.precomputed_embeddings = {}
        if precomputed_embeddings_path and os.path.exists(precomputed_embeddings_path):
            try:
                if TORCH_AVAILABLE:
                    self.precomputed_embeddings = torch.load(precomputed_embeddings_path, map_location='cpu', weights_only=True)
                    print(f"✅ Loaded {len(self.precomputed_embeddings)} pre-computed text embeddings")
                else:
                    print("⚠️  PyTorch not available, skipping pre-computed embeddings")
            except Exception as e:
                print(f"⚠️  Warning: Could not load pre-computed embeddings: {e}")
        elif precomputed_embeddings_path:
            print(f"⚠️  Warning: Pre-computed embeddings file not found: {precomputed_embeddings_path}")
        
        # Load the paired data
        self.paired_data = load_jsonl_file(paired_data_path)
        
        # Generate sequential training pairs from all methods
        self.sequential_pairs = []
        self._generate_all_sequential_pairs()
        
        print(f"Loaded {len(self.paired_data)} methods from {paired_data_path}")
        print(f"Generated {len(self.sequential_pairs)} sequential training pairs")
    
    def _generate_all_sequential_pairs(self):
        """Generate sequential training pairs from all ASTs in the dataset."""
        for sample in self.paired_data:
            try:
                # Get text description
                descriptions = sample.get('descriptions', [])
                if descriptions:
                    description = random.choice(descriptions)
                    text_description = description['text']
                else:
                    # Fallback to method name if no descriptions available
                    text_description = sample.get('method_name', 'unknown_method')
                
                # Create sequential pairs for this AST
                sequential_pairs = self._create_sequential_pairs(
                    sample['ast_json'], 
                    text_description
                )
                
                # Add to global list
                self.sequential_pairs.extend(sequential_pairs)
                
            except Exception as e:
                # Skip malformed samples gracefully
                print(f"Warning: Skipping sample {sample.get('id', 'unknown')} due to error: {e}")
                continue
    
    def _create_sequential_pairs(self, ast_json: str, text_description: str) -> List[Dict[str, Any]]:
        """
        Convert single AST into sequence of (partial_graph, target_node) pairs.
        
        Args:
            ast_json: JSON string representing the AST
            text_description: Text description for this method
            
        Returns:
            List of sequential training pairs
        """
        pairs = []
        
        try:
            # Extract nodes in proper order along with their connections
            nodes, connections = self._extract_nodes_and_connections_in_order(ast_json)
            
            # Limit sequence length if needed
            if len(nodes) > self.max_sequence_length:
                nodes = nodes[:self.max_sequence_length]
                # Also limit connections to only include those within the sequence
                filtered_connections = []
                for src, tgt in connections:
                    if src < self.max_sequence_length and tgt < self.max_sequence_length:
                        filtered_connections.append((src, tgt))
                connections = filtered_connections
            
            # Get pre-computed text embedding if available, otherwise store text
            text_embedding = None
            if text_description in self.precomputed_embeddings:
                text_embedding = self.precomputed_embeddings[text_description]
            
            # Create sequential pairs
            for i in range(len(nodes)):
                # Build partial graph with nodes 0 to i-1
                partial_graph = self._build_partial_graph(nodes[:i])
                
                # Target is the i-th node
                target_node = nodes[i]
                
                # Create target connections for this step
                # This represents which existing nodes (0 to i-1) the new node i should connect to
                target_connections = self._create_target_connections(i, connections)
                
                pair = {
                    'text_description': text_description,
                    'text_embedding': text_embedding,  # Pre-computed embedding if available
                    'partial_graph': partial_graph,
                    'target_node': target_node,
                    'target_connections': target_connections,
                    'step': i,
                    'total_steps': len(nodes)
                }
                
                pairs.append(pair)
                
        except Exception as e:
            # Return empty list for malformed ASTs
            print(f"Warning: Failed to create sequential pairs: {e}")
            
        return pairs
    
    def _extract_nodes_and_connections_in_order(self, ast_json: str) -> Tuple[List[Dict[str, Any]], List[Tuple[int, int]]]:
        """
        Extract nodes and their connections from AST in proper depth-first order.
        
        Args:
            ast_json: JSON string representing the AST
            
        Returns:
            Tuple of (nodes_list, connections_list) where connections are (parent_idx, child_idx) pairs
        """
        try:
            ast_data = json.loads(ast_json)
            nodes = []
            connections = []
            self._traverse_ast_nodes_with_connections(ast_data, nodes, connections, parent_idx=None)
            return nodes, connections
        except (json.JSONDecodeError, Exception):
            # Return empty lists for malformed JSON
            return [], []
    
    def _traverse_ast_nodes_with_connections(self, node: Union[Dict, List, str, int, float, None], 
                                           nodes: List[Dict[str, Any]], 
                                           connections: List[Tuple[int, int]],
                                           parent_idx: Optional[int] = None):
        """
        Recursively traverse AST and collect nodes and connections in depth-first order.
        
        Args:
            node: Current AST node
            nodes: List to collect nodes
            connections: List to collect connections as (parent_idx, child_idx) pairs
            parent_idx: Index of parent node
        """
        if isinstance(node, dict) and 'type' in node:
            # This is an AST node with a type
            current_idx = len(nodes)
            node_info = {
                'node_type': node['type'],
                'features': self.converter.node_encoder.create_node_features(node['type']),
                'raw_node': node  # Keep reference for debugging
            }
            nodes.append(node_info)
            
            # Add connection from parent to current node
            if parent_idx is not None:
                connections.append((parent_idx, current_idx))
            
            # Traverse children
            if 'children' in node:
                for child in node['children']:
                    self._traverse_ast_nodes_with_connections(child, nodes, connections, current_idx)
                    
        elif isinstance(node, list):
            # Process list of nodes
            for child in node:
                self._traverse_ast_nodes_with_connections(child, nodes, connections, parent_idx)
    
    def _create_target_connections(self, node_idx: int, all_connections: List[Tuple[int, int]]) -> List[float]:
        """
        Create target connection vector for a specific node being added.
        
        Args:
            node_idx: Index of the node being added to the graph
            all_connections: List of all connections in the full AST as (parent_idx, child_idx) pairs
            
        Returns:
            Binary vector of length max_nodes indicating which existing nodes to connect to
        """
        # Initialize with zeros for all possible connections
        target_vector = [0.0] * 100  # max_nodes = 100 from model
        
        # Find all connections where this node is the target (child)
        # We want to know which existing nodes (with index < node_idx) should connect to this node
        for parent_idx, child_idx in all_connections:
            if child_idx == node_idx and parent_idx < node_idx and parent_idx < 100:
                target_vector[parent_idx] = 1.0
        
        return target_vector
    
    def _traverse_ast_nodes(self, node: Union[Dict, List, str, int, float, None], nodes: List[Dict[str, Any]]):
        """
        Recursively traverse AST and collect nodes in depth-first order.
        
        Args:
            node: Current AST node
            nodes: List to collect nodes
        """
        if isinstance(node, dict) and 'type' in node:
            # This is an AST node with a type
            node_info = {
                'node_type': node['type'],
                'features': self.converter.node_encoder.create_node_features(node['type']),
                'raw_node': node  # Keep reference for debugging
            }
            nodes.append(node_info)
            
            # Traverse children
            if 'children' in node:
                for child in node['children']:
                    self._traverse_ast_nodes(child, nodes)
                    
        elif isinstance(node, list):
            # Process list of nodes
            for child in node:
                self._traverse_ast_nodes(child, nodes)
    
    def _build_partial_graph(self, nodes: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        Build partial graph from first i nodes.
        
        Args:
            nodes: List of nodes to include in partial graph
            
        Returns:
            Partial graph representation
        """
        if not nodes:
            # Empty graph case
            return {
                'x': [],
                'edge_index': [[], []],
                'num_nodes': 0
            }
        
        # Extract node features
        node_features = [node['features'] for node in nodes]
        
        # Create simple sequential connections (each node connects to next)
        # This is a simplified approach - in practice you'd want to preserve 
        # the actual AST structure relationships
        edge_list = []
        for i in range(len(nodes) - 1):
            edge_list.append([i, i + 1])  # Forward edge
            edge_list.append([i + 1, i])  # Backward edge for undirected
        
        if edge_list:
            edge_index = [[], []]
            for source, target in edge_list:
                edge_index[0].append(source)
                edge_index[1].append(target)
        else:
            edge_index = [[], []]
        
        return {
            'x': node_features,
            'edge_index': edge_index,
            'num_nodes': len(nodes)
        }
    
    def __len__(self) -> int:
        """Return the number of sequential training pairs."""
        return len(self.sequential_pairs)
    
    def __getitem__(self, idx: int) -> Dict[str, Any]:
        """
        Get a sequential training pair.
        
        Args:
            idx: Index of the training pair
            
        Returns:
            Dictionary containing partial graph and target node data
        """
        if idx < 0 or idx >= len(self.sequential_pairs):
            raise IndexError(f"Index {idx} out of range for dataset of size {len(self.sequential_pairs)}")
        
        return self.sequential_pairs[idx]
    
    def get_feature_dim(self) -> int:
        """Return the dimension of node features."""
        return self.converter.node_encoder.vocab_size


def collate_autoregressive_data(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Collate function for batching autoregressive training data.
    
    Args:
        batch: List of sequential training pairs
        
    Returns:
        Batched autoregressive training data
    """
    if not batch:
        raise ValueError("Cannot collate empty batch")
    
    # Separate different components
    text_descriptions = [item['text_description'] for item in batch]
    text_embeddings = [item.get('text_embedding') for item in batch]
    steps = [item['step'] for item in batch]
    total_steps = [item['total_steps'] for item in batch]
    
    # Collate partial graphs
    partial_graphs = [item['partial_graph'] for item in batch]
    
    # Collate node features from partial graphs
    all_x = []
    all_edge_index = [[], []]
    batch_idx = []
    node_offset = 0
    
    for i, graph in enumerate(partial_graphs):
        # Node features
        if graph['x']:
            all_x.extend(graph['x'])
            
            # Edge indices (offset by current node count)
            edges = graph['edge_index']
            if len(edges[0]) > 0:
                for j in range(len(edges[0])):
                    all_edge_index[0].append(edges[0][j] + node_offset)
                    all_edge_index[1].append(edges[1][j] + node_offset)
            
            # Batch indices for each node
            num_nodes = graph['num_nodes']
            batch_idx.extend([i] * num_nodes)
            node_offset += num_nodes
    
    # Target nodes and connections
    target_nodes = [item['target_node'] for item in batch]
    target_node_types = [node['node_type'] for node in target_nodes]
    target_node_features = [node['features'] for node in target_nodes]
    target_connections = [item['target_connections'] for item in batch]
    
    return {
        'text_descriptions': text_descriptions,
        'text_embeddings': text_embeddings,  # Can contain None values if not pre-computed
        'partial_graphs': {
            'x': all_x,
            'edge_index': all_edge_index,
            'batch': batch_idx,
            'num_graphs': len(batch)
        },
        'target_node_types': target_node_types,
        'target_node_features': target_node_features,
        'target_connections': target_connections,
        'steps': steps,
        'total_steps': total_steps
    }


class AutoregressiveDataLoader:
    """
    DataLoader for autoregressive AST training data.
    """
    
    def __init__(self, dataset: AutoregressiveASTDataset, batch_size: int = 8, shuffle: bool = True):
        """
        Initialize the AutoregressiveDataLoader.
        
        Args:
            dataset: AutoregressiveASTDataset to load from
            batch_size: Number of sequential pairs per batch
            shuffle: Whether to shuffle the data
        """
        self.dataset = dataset
        self.batch_size = batch_size
        self.shuffle = shuffle
        
        # Create indices
        self.indices = list(range(len(dataset)))
        if shuffle:
            random.shuffle(self.indices)
    
    def __len__(self) -> int:
        """Return number of batches."""
        return (len(self.dataset) + self.batch_size - 1) // self.batch_size
    
    def __iter__(self):
        """Iterate over batches."""
        for i in range(0, len(self.dataset), self.batch_size):
            batch_indices = self.indices[i:i + self.batch_size]
            batch = [self.dataset[idx] for idx in batch_indices]
            yield collate_autoregressive_data(batch)


def create_autoregressive_data_loader(paired_data_path: str, batch_size: int = 8, shuffle: bool = True, 
                                    max_sequence_length: int = 50, seed: Optional[int] = None,
                                    precomputed_embeddings_path: Optional[str] = None,
                                    num_workers: Optional[int] = None, pin_memory: bool = True):
    """
    Create data loader for autoregressive AST training.
    
    Args:
        paired_data_path: Path to paired_data.jsonl file
        batch_size: Number of sequential pairs per batch
        shuffle: Whether to shuffle the data
        max_sequence_length: Maximum sequence length per method
        seed: Random seed for consistent description sampling
        precomputed_embeddings_path: Path to pre-computed text embeddings file
        num_workers: Number of worker processes for data loading (defaults to CPU count)
        pin_memory: Whether to use pinned memory for faster GPU transfer
        
    Returns:
        DataLoader instance (PyTorch DataLoader if available, otherwise AutoregressiveDataLoader)
    """
    dataset = AutoregressiveASTDataset(
        paired_data_path, 
        max_sequence_length=max_sequence_length, 
        seed=seed,
        precomputed_embeddings_path=precomputed_embeddings_path
    )
    
    # Use PyTorch DataLoader if available for better performance
    if TORCH_AVAILABLE:
        import os
        if num_workers is None:
            num_workers = os.cpu_count()
        
        try:
            from torch.utils.data import DataLoader
            
            # Create PyTorch DataLoader with optimizations
            loader = DataLoader(
                dataset,
                batch_size=batch_size,
                shuffle=shuffle,
                num_workers=num_workers,
                pin_memory=pin_memory and torch.cuda.is_available(),
                collate_fn=collate_autoregressive_data,
                persistent_workers=num_workers > 0,  # Keep workers alive between epochs
                prefetch_factor=2 if num_workers > 0 else 2  # Prefetch batches
            )
            
            print(f"✅ Using optimized PyTorch DataLoader with {num_workers} workers, pin_memory={pin_memory and torch.cuda.is_available()}")
            return loader
            
        except Exception as e:
            print(f"⚠️  Warning: Could not create PyTorch DataLoader ({e}), falling back to custom loader")
    
    # Fallback to custom loader
    loader = AutoregressiveDataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
    print("ℹ️  Using custom AutoregressiveDataLoader")
    
    return loader


class HierarchicalASTDataset(RubyASTDataset):
    """
    Dataset for loading a single level of a hierarchical AST dataset.

    This class inherits from RubyASTDataset to reuse the same AST-to-graph
    conversion logic. It is used to load one of the `_level_N.jsonl` files.
    """
    def __init__(self, jsonl_path: str, transform=None):
        """
        Initialize the dataset for a specific AST level.

        Args:
            jsonl_path: Path to the JSONL file for a specific level.
            transform: Optional transform to apply to each sample.
        """
        super().__init__(jsonl_path, transform)


def create_hierarchical_data_loader(dataset_path: str, batch_size: int, shuffle: bool, num_workers: Optional[int] = None):
    """
    Creates a data loader for a specific level of the hierarchical dataset.

    Args:
        dataset_path: The full path to the `_level_N.jsonl` file.
        batch_size: The batch size for the data loader.
        shuffle: Whether to shuffle the data.
        num_workers: The number of worker processes for data loading.

    Returns:
        A DataLoader instance for the specified dataset level.
    """
    dataset = HierarchicalASTDataset(dataset_path)

    if TORCH_AVAILABLE:
        try:
            from torch_geometric.loader import DataLoader
            if num_workers is None:
                num_workers = os.cpu_count()
            
            loader = DataLoader(
                dataset,
                batch_size=batch_size,
                shuffle=shuffle,
                num_workers=num_workers,
                pin_memory=torch.cuda.is_available(),
                persistent_workers=num_workers > 0,
                collate_fn=collate_graphs # Reusing the existing collate function
            )
            logging.info(f"Created PyG DataLoader for {dataset_path} with {num_workers} workers.")
            return loader
        except ImportError:
            logging.warning("PyTorch Geometric not found. Falling back to SimpleDataLoader.")
    
    # Fallback to SimpleDataLoader
    return SimpleDataLoader(dataset, batch_size=batch_size, shuffle=shuffle, collate_fn=collate_graphs)


class HierarchicalPairedDataset(PairedDataset):
    """
    Dataset for loading a single level of a hierarchical dataset with paired text.

    This class inherits from PairedDataset to reuse the same logic for
    processing graph data and randomly sampling text descriptions.
    """
    def __init__(self, jsonl_path: str, transform=None, seed: Optional[int] = None, limit: Optional[int] = None):
        """
        Initialize the dataset for a specific AST level.

        Args:
            jsonl_path: Path to the JSONL file for a specific level (e.g., train_paired_data_level_0.jsonl).
            transform: Optional transform to apply to each sample.
            seed: Random seed for consistent description sampling.
            limit: Optional maximum number of samples to load.
        """
        super().__init__(jsonl_path, transform, seed, limit)


def create_hierarchical_paired_data_loader(dataset_path: str, batch_size: int, shuffle: bool, num_workers: Optional[int] = None, limit: Optional[int] = None):
    """
    Creates a data loader for a specific level of the hierarchical paired dataset.

    Args:
        dataset_path: The full path to the `_level_N.jsonl` file.
        batch_size: The batch size for the data loader.
        shuffle: Whether to shuffle the data.
        num_workers: The number of worker processes for data loading.
        limit: Optional maximum number of samples to load.

    Returns:
        A DataLoader instance for the specified dataset level.
    """
    dataset = HierarchicalPairedDataset(dataset_path, limit=limit)

    if TORCH_AVAILABLE:
        try:
            from torch.utils.data import DataLoader
            if num_workers is None:
                num_workers = 0 # Disabled for now to prevent file handle exhaustion
            
            loader = DataLoader(
                dataset,
                batch_size=batch_size,
                shuffle=shuffle,
                num_workers=num_workers,
                pin_memory=torch.cuda.is_available(),
                persistent_workers=num_workers > 0,
                collate_fn=collate_paired_data
            )
            logging.info(f"Created PyTorch DataLoader for {dataset_path} with {num_workers} workers.")
            return loader
        except (ImportError, Exception) as e:
            logging.warning(f"PyTorch DataLoader creation failed ({e}). Falling back to PairedDataLoader.")

    # Fallback to custom PairedDataLoader
    return PairedDataLoader(dataset, batch_size=batch_size, shuffle=shuffle)