"""Draw the two exact retained circuit partitions for the reader."""
import json
from pathlib import Path


HERE = Path(__file__).resolve().parent
COLORS = ('#096675', '#a74326', '#654887')


def circuit(word, x, y, step):
    vertices = [(x+step*edge[0][1], y+step*edge[0][0]) for edge in word]

    def inset(a, b):
        return tuple(.83*v+.17*w for v, w in zip(a, b))

    def point(pair):
        return ' '.join(f'{value:.2f}' for value in pair)

    commands = ['M' + point(inset(vertices[0], vertices[1]))]
    for i in range(1, len(vertices)+1):
        a, b, c = vertices[i-1], vertices[i%len(vertices)], vertices[(i+1)%len(vertices)]
        commands.extend(['L' + point(inset(b, a)), 'Q' + point(b) + ' ' + point(inset(b, c))])
    return ' '.join(commands) + ' Z'


def render(data):
    svg = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 350" width="760" height="350">',
           '<title>One circuit and three circuits with identical cubic counts</title>',
           '<rect width="760" height="350" rx="8" fill="#f5f7ed"/>']
    for index, words in enumerate(data['words']):
        x,y,step = 35+380*index, 53, 38
        lengths = sorted(map(len, words))
        label = 'A · one circuit' if index == 0 else 'B · three circuits'
        svg.append(f'<text x="{x}" y="32" fill="#1b302d" font-family="sans-serif" font-size="21">{label}</text>')
        for word, color in zip(words, COLORS, strict=False):
            svg.append(f'<path d="{circuit(word,x,y,step)}" fill="none" stroke="{color}" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>')
        values = ', '.join(map(str,lengths))
        svg.append(f'<text x="{x}" y="338" fill="#405952" font-family="sans-serif" font-size="17">Circuit lengths: {values}</text>')
    svg.append('</svg>')
    return '\n'.join(svg) + '\n'


if __name__ == '__main__':
    witness = json.loads((HERE.parent / 'companion' / 'N6.json').read_bytes())
    (HERE / 'n6-circuits.svg').write_bytes(render(witness).encode('utf-8'))
