import subprocess, os

# Re-extract JS with correct encoding and apply all fixes
result = subprocess.run(['git', 'show', 'c663627:p44-ocr-viewer.js'], capture_output=True, cwd=os.path.dirname(__file__))
content = result.stdout.decode('utf-8')

# Fix paths: ./Inputs/ -> ../Inputs/
content = content.replace('./Inputs/', '../Inputs/')

# Fix server data file paths to include viewer/data/ prefix
content = content.replace("const SERVER_FLAGS_FILE       = 'flags-'",       "const SERVER_FLAGS_FILE       = 'viewer/data/flags-'")
content = content.replace("const SERVER_PASS2_FLAGS_FILE = 'pass2_flags-'", "const SERVER_PASS2_FLAGS_FILE = 'viewer/data/pass2_flags-'")
content = content.replace("const SERVER_CORRECTIONS_FILE = 'corrections-'", "const SERVER_CORRECTIONS_FILE = 'viewer/data/corrections-'")

# Add cache-buster to MD fetch
content = content.replace(
    'fetch(REAL_TEXT_PATH).then',
    "fetch(REAL_TEXT_PATH + '?v=' + Date.now()).then"
)

# Add saveCurrentPage guard (prevent saving pages outside loaded MD range)
old_guard = (
    'function saveCurrentPage() {\n'
    '  const pageNum    = parseInt(textEditor.dataset.page, 10);\n'
    '  if (!pageNum) return;'
)
new_guard = (
    'function saveCurrentPage() {\n'
    '  const pageNum    = parseInt(textEditor.dataset.page, 10);\n'
    '  if (!pageNum) return;\n'
    '  if (!state.ocrPages[pageNum]) return;  // do not save pages outside loaded MD range'
)
content = content.replace(old_guard, new_guard)

out_path = os.path.join(os.path.dirname(__file__), 'viewer', 'p44-ocr-viewer.js')
with open(out_path, 'w', encoding='utf-8', newline='\n') as f:
    f.write(content)

print(f'Done. Lines: {content.count(chr(10))}')
print('Paths check:')
for line in content.splitlines():
    if 'pdfPath' in line or 'textPath' in line or 'SERVER_FLAGS_FILE' in line or 'SERVER_CORRECTIONS' in line or 'ocrPages[pageNum]' in line or 'Date.now' in line:
        print(' ', line.strip())

