"""
Fix the structural JSON error in ar.json.

The error is at specific line numbers:
  - One line ends with double comma ,,
  - Two lines have wrong indentation / missing trailing comma
  - The following line is missing a preceding comma separator

Strategy: read lines, patch the specific lines by index, validate JSON.
"""

import json, sys

SRC = "apps/frontend/messages/ar.json"

with open(SRC, encoding="utf-8") as fh:
    lines = fh.readlines()

# Find the line with the double comma (the broken "enter_new_address" line)
for i, line in enumerate(lines):
    if '"enter_new_address"' in line and line.rstrip().endswith(',,'):
        # Fix the double comma
        lines[i] = line.rstrip().rstrip(',') + ',\n'
        bad_line = i
        print(f"Fixed double-comma on line {i+1}")
        break
else:
    print("Double-comma line not found — already fixed or pattern changed.")
    bad_line = None

# Fix the two injected lines that follow: wrong indentation, last one missing comma
# They look like:
#     '    "no_saved_addresses": "...",\n'   <- 4-space indent (wrong)
#     '    "add_first_address": "..."\n'     <- 4-space indent, no comma
# Followed by:
#     '                                   "selected_address_summary": ...'  <- no preceding comma

if bad_line is not None:
    # The two injected lines should be right after bad_line
    j = bad_line + 1
    while j < len(lines) and lines[j].strip() == '':
        j += 1

    proper_indent = ' ' * 35  # match surrounding lines (35 spaces)

    if j < len(lines) and '"no_saved_addresses"' in lines[j]:
        # Re-indent and ensure trailing comma
        val = lines[j].strip().rstrip(',') + ','
        lines[j] = proper_indent + val + '\n'
        print(f"Fixed indent on line {j+1}: no_saved_addresses")

    k = j + 1
    while k < len(lines) and lines[k].strip() == '':
        k += 1

    if k < len(lines) and '"add_first_address"' in lines[k]:
        # Re-indent and add trailing comma (needed before "selected_address_summary")
        val = lines[k].strip().rstrip(',') + ','
        lines[k] = proper_indent + val + '\n'
        print(f"Fixed indent+comma on line {k+1}: add_first_address")

# Validate
text = ''.join(lines)
try:
    json.loads(text)
except json.JSONDecodeError as e:
    print(f"\nERROR: JSON still invalid: {e}")
    # Show context around error
    err_line = e.lineno - 1
    for x in range(max(0, err_line - 3), min(len(lines), err_line + 4)):
        marker = ">>>" if x == err_line else "   "
        print(f"{marker} {x+1}: {lines[x]}", end='')
    sys.exit(1)

with open(SRC, "w", encoding="utf-8") as fh:
    fh.write(text)

print("\nDone — ar.json is now valid JSON.")
