"""
Put the Dev Inspect panel (inspect.css + inspect.js) into the prototypes:

    python dev-inspect/apply.py

Edits Customer.html, Provide.html and the Arabic copies in place. Safe to run
again: the block between the DEV-INSPECT markers is replaced each time.
Edit inspect.css / inspect.js here, never the copies inside the HTML files.
"""
import os
import re

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
FILES = ['Customer.html', 'Provide.html', 'Arabic/Customer.html', 'Arabic/Provide.html']

css = open(os.path.join(HERE, 'inspect.css'), encoding='utf-8').read().strip()
js = open(os.path.join(HERE, 'inspect.js'), encoding='utf-8').read().strip()
CSS_BLOCK = '<!-- DEV-INSPECT:CSS:START -->\n<style>\n' + css + '\n</style>\n<!-- DEV-INSPECT:CSS:END -->\n'
JS_BLOCK = '/* DEV-INSPECT:JS:START */\n' + js + '\n/* DEV-INSPECT:JS:END */\n'

for name in FILES:
    path = os.path.join(ROOT, name)
    src = open(path, encoding='utf-8').read()
    src = re.sub(r'<!-- DEV-INSPECT:CSS:START -->.*?<!-- DEV-INSPECT:CSS:END -->\n', '', src, flags=re.S)
    src = re.sub(r'/\* DEV-INSPECT:JS:START \*/.*?/\* DEV-INSPECT:JS:END \*/\n', '', src, flags=re.S)
    if src.count('<div class="shell">') != 1 or src.count('\ninitViewer();') != 1:
        raise SystemExit(f'{name}: could not find the viewer shell or initViewer(); call')
    src = src.replace('<div class="shell">', CSS_BLOCK + '<div class="shell">', 1)
    # Before initViewer(): the panel must exist before the first screen paints its notes.
    src = src.replace('\ninitViewer();', '\n' + JS_BLOCK + 'initViewer();', 1)
    open(path, 'w', encoding='utf-8', newline='\r\n').write(src)  # the prototypes use CRLF line endings
    print('updated', name)
