# git show :stage:filename
# common ancestor: 1
# HEAD: 2
# MERGE_HEAD: 3

import re
from subprocess import Popen, PIPE
import sys

BASE = 1
HEAD = 2
MERGE_HEAD = 3
FINAL = 0

outputs = {}

for stage in (BASE, HEAD, MERGE_HEAD):
    p = Popen(['git', 'show', f':{stage}:keyfreq'], stdout=PIPE, stderr=PIPE)
    output, err = p.communicate()

    if p.returncode:
        print(output)
        sys.exit(1)

    outputs[stage] = {}

    if b'"' in output:
        raise ValueError(f'There is a " in the output of stage {stage}')

    output = output.decode('utf-8')[1:-1].split('\n')

    for line in output:
        line = line.strip()

        if not line:
            continue

        m = re.match(r'^\(\(([^) ]+) .\ ([^) ]+)\) \. ([0-9]+)\)$', line)

        if not m:
            raise ValueError(f'Invalid cons cell: {line}')

        mode, command, count = m.groups()
        count = int(count)

        outputs[stage].setdefault(mode, {})
        outputs[stage][mode][command] = count


outputs[FINAL] = {}

for stage in (BASE, HEAD, MERGE_HEAD):
    for mode in outputs[stage]:
        outputs[FINAL][mode] = {}

        for command, count in outputs[stage][mode].items():
            base_mode = outputs[BASE].get(mode, {})
            base_count = base_mode.get(command, 0)
            this_count = outputs[stage][mode][command]

            outputs[FINAL][mode].setdefault(command, base_count)
            
            if stage != BASE:
                outputs[FINAL][mode][command] += this_count - base_count

output = '('
for mode in outputs[FINAL]:
    for command, count in outputs[FINAL][mode].items():
        output += f'(({mode} . {command}) . {count})\n'

output = output[:-1] + ')'

with open('keyfreq', 'w') as f:
    f.write(output)