import copy
import json
import subprocess
from pathlib import Path


def git(*args, data=None):
    return subprocess.run(
        ['git', *args], input=data, check=True, capture_output=True
    ).stdout


assert not git('diff', '--cached', '--name-only').strip(), 'Index already contains changes'
path = 'tools/chantiers/data/chantiers.json'
base_text = git('show', 'HEAD:' + path).decode('utf-8')
base = json.loads(base_text)
assert json.dumps(base, ensure_ascii=False, indent=4) + '\n' == base_text.replace('\r\n', '\n')
live_before = Path(path).read_bytes()
live = json.loads(live_before.decode('utf-8-sig'))
record = next(item for item in live['items'] if item['id'] == 91)
assert record['status'] == 'Terminé'
assert not any(item['id'] == 91 for item in base['items'])
staged = copy.deepcopy(base)
staged['items'].append(record)
staged['next_id'] = max(base['next_id'], 92)
encoded = (json.dumps(staged, ensure_ascii=False, indent=4) + '\n').encode('utf-8')
oid = git('hash-object', '-w', '--stdin', data=encoded).decode().strip()
git('add', '--', 'docs/current-task.md')
git('update-index', '--add', '--cacheinfo', '100644', oid, path)
paths = set(git('diff', '--cached', '--name-only').decode().splitlines())
assert paths == {'docs/current-task.md', path}, paths
index_data = json.loads(git('show', ':' + path))
old = {item['id']: item for item in base['items']}
new = {item['id']: item for item in index_data['items']}
assert [key for key in new if old.get(key) != new[key]] == [91]
assert old.keys() <= new.keys()
assert Path(path).read_bytes() == live_before, 'Working tracker changed unexpectedly'
git('diff', '--cached', '--check')
print(git('commit', '-m', 'Chantiers : ligne 91 terminee, validation et releve').decode('utf-8', errors='replace'))
assert Path(path).read_bytes() == live_before, 'Commit modified working tracker'
print('Only record 91 committed; records 90/92 and all working data preserved.')
