#!/usr/bin/env python3
"""Apply the list indexing/slicing fix"""

# Read the file
with open('nxcypher/__init__.py', 'r') as f:
    lines = f.readlines()

# Find the section to replace (starting at line 4140, 0-indexed 4139)
# The old code is from line 4140 to line 4164 (inclusive, 0-indexed 4139 to 4163)
start_line = 4139  # 0-indexed
end_line = 4164    # 0-indexed, exclusive

old_section = ''.join(lines[start_line:end_line])
print("Old section:")
print(old_section)
print("\n" + "="*60 + "\n")

new_section = """            else:
                # List indexing or slicing: [expr] or [expr..expr]
                has_range = _has_token_v4(child, "RANGE")
                if has_range:
                    # Slice: base[start..end]
                    # Need to find which expressions are before/after the RANGE token
                    # Grammar: LBRACK (expression? RANGE expression? | expression) RBRACK
                    range_idx = None
                    for i, c in enumerate(child.children):
                        if isinstance(c, Token) and c.type == "RANGE":
                            range_idx = i
                            break

                    # Get expressions before and after RANGE
                    start_expr = None
                    end_expr = None
                    if range_idx is not None:
                        # Find expression before RANGE
                        for i in range(range_idx - 1, -1, -1):
                            c = child.children[i]
                            if isinstance(c, Tree):
                                start_expr = c
                                break
                        # Find expression after RANGE
                        for i in range(range_idx + 1, len(child.children)):
                            c = child.children[i]
                            if isinstance(c, Tree):
                                end_expr = c
                                break

                    start_val = self._eval_expression(start_expr, ctx) if start_expr else None
                    end_val = self._eval_expression(end_expr, ctx) if end_expr else None

                    if base is None:
                        return None

                    # Check for null in slice bounds - return null if either bound is explicitly null
                    if (start_expr is not None and start_val is None) or (end_expr is not None and end_val is None):
                        return None

                    start_i = int(start_val) if start_val is not None else None
                    end_i = int(end_val) if end_val is not None else None
                    try:
                        return base[start_i:end_i]
                    except (TypeError, IndexError):
                        return None
                else:
                    exprs = [c for c in child.children if isinstance(c, Tree)]
                    if exprs:
                        # Index: base[expr]
                        idx = self._eval_expression(exprs[0], ctx)
                        if base is None or idx is None:
                            return None
                        try:
                            return base[int(idx)]
                        except (TypeError, IndexError, KeyError):
                            return None
            return None
"""

print("New section:")
print(new_section)
print("\n" + "="*60 + "\n")

# Replace the section
new_lines = lines[:start_line] + [new_section] + lines[end_line:]

# Write back
with open('nxcypher/__init__.py', 'w') as f:
    f.writelines(new_lines)

print("Fix applied successfully!")
