#!/usr/bin/env python3
"""Fix WHERE clause handling for OPTIONAL MATCH"""

import sys

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

# Find the section to replace
old_code = """                            result = self._eval_expression(self._where_expression, ctx)
                            if not result:
                                continue"""

new_code = """                            result = self._eval_expression(self._where_expression, ctx)
                            if not result:
                                # Check if WHERE references any optional variables that are null
                                # If so, this is expected (OPTIONAL MATCH didn't find anything),
                                # so we should NOT filter out the base row
                                where_refs_optional_null = any(
                                    current_match.get(node) is None
                                    for node in self._optional_nodes
                                    if node in current_match
                                )
                                # Only skip this match if WHERE failed on required variables,
                                # not because optional variables are null
                                if not where_refs_optional_null:
                                    continue"""

# Replace - but only in the OPTIONAL MATCH section (after "for base_match in base_matches:")
# Find the pattern by looking for context
pattern_start = "for base_match in base_matches:"
pattern_end = "# Fallback for old-style optional handling"

start_idx = content.find(pattern_start)
end_idx = content.find(pattern_end, start_idx)

if start_idx == -1 or end_idx == -1:
    print("Error: Could not find the OPTIONAL MATCH section")
    sys.exit(1)

section = content[start_idx:end_idx]
if old_code not in section:
    print("Error: Could not find the old code in the OPTIONAL MATCH section")
    sys.exit(1)

# Replace only in this section
new_section = section.replace(old_code, new_code, 1)
new_content = content[:start_idx] + new_section + content[end_idx:]

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

print("Successfully patched nxcypher/__init__.py")
