#!/usr/bin/python3
"""Record upstream editable content and protect local changes during updates."""
import hashlib
import json
from pathlib import Path
import sys


def files(root):
    return {
        str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
        for path in (root / 'includes/languages').glob('*/html_includes/**/*')
        if path.is_file()
    }


def main():
    if len(sys.argv) == 4 and sys.argv[1] == 'record':
        root, output = map(Path, sys.argv[2:])
        output.write_text(json.dumps(files(root), sort_keys=True) + '\n')
        return
    if len(sys.argv) != 6 or sys.argv[1] != 'plan':
        raise SystemExit('usage: content-update-plan record ROOT FILE | plan INSTALLED CANDIDATE BASELINE EXCLUDES')
    installed, candidate, baseline, excludes = map(Path, sys.argv[2:])
    old = json.loads(baseline.read_text())
    current, incoming = files(installed), files(candidate)
    preserved, conflicts = [], []
    for path, new_hash in incoming.items():
        local_hash, old_hash = current.get(path), old.get(path)
        if local_hash == new_hash or local_hash == old_hash:
            continue
        if old_hash is not None and new_hash == old_hash:
            preserved.append('/' + path)
        elif local_hash is not None or old_hash is not None:
            conflicts.append(path)
    if conflicts:
        raise SystemExit('editable Zen Cart content conflicts with the update: ' + ', '.join(sorted(conflicts)))
    excludes.write_text(''.join(path + '\n' for path in sorted(preserved)))


if __name__ == '__main__':
    main()
