"""Draw vector figures from the exact retained circuit words with stdlib only."""
import argparse
from pathlib import Path

from verify import load


COLORS = ((.02,.37,.43), (.68,.24,.10), (.37,.24,.56))


def text(value, x, y, size=11):
    safe = value.replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
    return f'0.09 0.15 0.18 rg BT /F1 {size} Tf {x} {y} Td ({safe}) Tj ET'


def point(value):
    return ' '.join(f'{v:.3f}' for v in value)


def circuit(vertices, origin, unit, color):
    x,y = origin
    vertices = [(x+c*unit, y-r*unit) for r,c in vertices]
    radius = .17

    def inset(a, b):
        return tuple((1-radius)*v+radius*w for v,w in zip(a,b))

    def control(start, end):
        return tuple((v+2*w)/3 for v,w in zip(start,end))

    commands = [f'{point(color)} RG 2.1 w 1 J 1 j',
                f'{point(inset(vertices[0], vertices[1]))} m']
    for i in range(1,len(vertices)+1):
        a,b,c = vertices[i-1], vertices[i % len(vertices)], vertices[(i+1) % len(vertices)]
        enter,leave = inset(b,a), inset(b,c)
        commands.extend([f'{point(enter)} l',
                         f'{point(control(enter,b))} {point(control(leave,b))} {point(leave)} c'])
    commands.append('h S')
    return '\n'.join(commands)


def panel(label, words, origin, unit, n):
    x,y = origin
    commands = [text(label,x,y+13), '0.84 0.87 0.86 rg']
    for r in range(1,n+1):
        for c in range(1,n+1):
            commands.append(f'{x+c*unit-.65:.3f} {y-r*unit-.65:.3f} 1.3 1.3 re f')
    for vertices,color in zip(words,COLORS):
        commands.append(circuit(vertices, origin, unit, color))
    return commands


def write_pdf(path, width, height, drawing):
    stream = '\n'.join(drawing).encode('ascii')
    objects = [
        b'<< /Type /Catalog /Pages 2 0 R >>',
        b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
        (f'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {width} {height}] '
         '/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>').encode(),
        b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
        f'<< /Length {len(stream)} >>\nstream\n'.encode() + stream + b'\nendstream',
    ]
    pdf = bytearray(b'%PDF-1.4\n')
    offsets = [0]
    for number, obj in enumerate(objects,1):
        offsets.append(len(pdf))
        pdf.extend(f'{number} 0 obj\n'.encode() + obj + b'\nendobj\n')
    xref = len(pdf)
    pdf.extend(f'xref\n0 {len(offsets)}\n0000000000 65535 f \n'.encode())
    for offset in offsets[1:]:
        pdf.extend(f'{offset:010d} 00000 n \n'.encode())
    pdf.extend(f'trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n'.encode())
    with path.open('xb') as target:
        target.write(pdf)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('output', type=Path, help='existing directory, with no target PDFs')
    args = parser.parse_args()
    seeds = load('seed_certificate.json')['targets']
    n6 = load('N6.json')['words']
    drawing = []
    for i,code in enumerate(('ADFD','AFBD','AEF7','AF77')):
        item = seeds[code]
        count = item['circuit_count']
        label = f'{code}: {count} ' + ('circuit' if count == 1 else 'circuits')
        drawing.extend(panel(label, [row['vertices'] for row in item['circuits']],
                             (18+188*(i%2), 308-164*(i//2)), 25, 4))
    write_pdf(args.output / 'r5l-seeds.pdf', 372, 337, drawing)
    drawing = []
    for i,words in enumerate(n6):
        label = ('A: 1 circuit (100 edges)', 'B: 3 circuits (24, 36, 40 edges)')[i]
        drawing.extend(panel(label, [[edge[0] for edge in word] for word in words],
                             (16+198*i, 191), 24, 6))
    write_pdf(args.output / 'n6-witness.pdf', 400, 221, drawing)


if __name__ == '__main__':
    main()
