import sys
import os

path = '/Users/marcmintel/Projects/at-mintel/packages/cms-infra/schema/snapshot.yaml'
if not os.path.exists(path):
    print(f"File not found: {path}")
    sys.exit(1)

with open(path, 'r') as f:
    lines = f.readlines()

new_lines = []
current_collection = None
current_field = None
in_schema = False

fix_fields = {'id', 'company', 'user_created', 'user_updated', 'screenshot', 'logo', 'feedback_id'}
uuid_fields = {'id', 'company', 'user_created', 'user_updated'}

# For multi-pass logic
snapshot_has_feedback_id = False

for line in lines:
    stripped = line.strip()
    
    if stripped.startswith('- collection:'):
        current_collection = stripped.split(':')[-1].strip()
        in_schema = False
    elif stripped.startswith('field:'):
        current_field = stripped.split(':')[-1].strip()
        if current_collection == 'visual_feedback_comments' and current_field == 'feedback_id':
             snapshot_has_feedback_id = True
    elif stripped == 'schema:':
        in_schema = True
    elif stripped == 'meta:' or stripped.startswith('- collection:') or (not line.startswith(' ') and line.strip() and not line.startswith('-')):
        in_schema = False
        
    # Top-level field type
    if not in_schema and stripped.startswith('type:') and current_field in uuid_fields:
        line = line.replace('type: string', 'type: uuid')
    
    # Schema data type
    if in_schema and current_field in fix_fields:
        if 'data_type: char' in line or 'data_type: varchar' in line:
            line = line.replace('data_type: char', 'data_type: uuid').replace('data_type: varchar', 'data_type: uuid')
        if 'max_length:' in line:
            line = '      max_length: null\n'
            
    new_lines.append(line)

# Handle Missing feedback_id Injection
if not snapshot_has_feedback_id:
    # We find systemFields and inject before it
    injected = False
    final_lines = []
    feedback_id_block = """  - collection: visual_feedback_comments
    field: feedback_id
    type: integer
    meta:
      collection: visual_feedback_comments
      field: feedback_id
      interface: select-dropdown-m2o
      required: true
      sort: 4
      width: full
    schema:
      name: feedback_id
      table: visual_feedback_comments
      data_type: integer
      is_nullable: false
      is_indexed: true
      foreign_key_table: visual_feedback
      foreign_key_column: id
"""
    for line in new_lines:
        if 'systemFields:' in line and not injected:
            final_lines.append(feedback_id_block)
            injected = True
        final_lines.append(line)
    new_lines = final_lines

# Second pass for primary key nullability
final_lines = []
for i in range(len(new_lines)):
    line = new_lines[i]
    if 'is_primary_key: true' in line:
        # Search backwards and forwards
        for j in range(max(0, i-10), min(len(new_lines), i+10)):
            if 'is_nullable: true' in new_lines[j]:
                new_lines[j] = new_lines[j].replace('is_nullable: true', 'is_nullable: false')
    final_lines.append(line)

with open(path, 'w') as f:
    f.writelines(new_lines)

print("SUCCESS: Full normalization and field injection complete.")
