"""Copia a fonte única de conferências (conferencias.js) para dentro dos protótipos que conferem textos.

Uso, a partir da raiz do projeto:
    .venv\\Scripts\\python.exe prototipos\\compartilhado\\aplicar.py            copia para os protótipos
    .venv\\Scripts\\python.exe prototipos\\compartilhado\\aplicar.py --conferir  só confere se as cópias batem (sai com 1 se não)

O bloco fica entre os marcadores /* conferencias:inicio */ e /* conferencias:fim */, logo depois do 'use strict'
do script principal. Cada protótipo é um arquivo único (vira uma página publicada sozinha), por isso a cópia.
"""
import sys
from pathlib import Path

AQUI = Path(__file__).resolve().parent
PROTOS = AQUI.parent
FONTE = AQUI / 'conferencias.js'
ALVOS = ['copiloto-recepcao.html', 'copiloto-suellen.html', 'copiloto-ana.html']
INICIO = '  /* conferencias:inicio */\n'
FIM = '  /* conferencias:fim */\n'


def bloco():
    return INICIO + FONTE.read_text(encoding='utf-8').rstrip('\n') + '\n' + FIM


def com_bloco(html, novo):
    if INICIO in html:
        i = html.index(INICIO)
        j = html.index(FIM, i) + len(FIM)
        return html[:i] + novo + html[j:]
    ancora = "'use strict';\n"
    i = html.index('<script>')
    k = html.index(ancora, i) + len(ancora)
    return html[:k] + novo + html[k:]


def main():
    conferir = '--conferir' in sys.argv
    novo = bloco()
    diferentes = []
    for nome in ALVOS:
        p = PROTOS / nome
        with open(p, encoding='utf-8', newline='') as f:
            html = f.read()
        saida = com_bloco(html, novo)
        if saida != html:
            diferentes.append(nome)
            if not conferir:
                with open(p, 'w', encoding='utf-8', newline='') as f:
                    f.write(saida)
    if conferir:
        for nome in diferentes:
            print(f'{nome}: a cópia das conferências está diferente da fonte; rode aplicar.py')
        sys.exit(1 if diferentes else 0)
    print('atualizados:', ', '.join(diferentes) if diferentes else 'nenhum (já estavam iguais)')


if __name__ == '__main__':
    main()
