"""Editable source for the O2AT Type 1 / Type 2 architecture comparison SVGs.

Run: python3 public/diagrams/architecture-comparison-source.py
The two output files are reviewed, static SVGs. This is an explanatory view,
not a change to the v0.2 wire protocol.
"""

from pathlib import Path
from xml.sax.saxutils import escape

OUT = Path(__file__).parent
INK = '#f3f4f6'
MUTED = '#c6d5e2'
AUDIO = '#38bdf8'
CONTROL = '#fbbf24'
CLOCK = '#34d399'

PANELS = [
    {
        'name': 'TYPE 1', 'status': 'v0.2 baseline', 'ports': 'One duplex SFP per endpoint',
        'lanes': [
            ('Audio frames', 'source to DAC', AUDIO, 'forward'),
            ('Receiver credits', 'DAC to source', CONTROL, 'return'),
        ],
        'note': 'DAC conversion clock stays local.',
    },
    {
        'name': 'TYPE 2A', 'status': 'proposed reverse reference', 'ports': 'One duplex SFP per endpoint',
        'lanes': [
            ('Audio frames', 'source to DAC', AUDIO, 'forward'),
            ('Candidate coded carrier', 'DAC to source', CLOCK, 'return'),
        ],
        'note': 'Clock-only return needs defined control.',
    },
    {
        'name': 'TYPE 2B', 'status': 'proposed forward reference', 'ports': 'Two optical ports per endpoint',
        'lanes': [
            ('Port 1 audio', 'source to DAC', AUDIO, 'forward'),
            ('Port 1 credits', 'DAC to source', CONTROL, 'return'),
            ('Port 2 reference', 'master to DAC', CLOCK, 'forward'),
        ],
        'note': 'Reference path needs qualification.',
    },
]


def rect(x, y, w, h, fill, stroke, radius=10, sw=1.5):
    return f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{radius}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>'


def text(x, y, value, size=15, fill=INK, weight=400, anchor='start'):
    return f'<text x="{x}" y="{y}" fill="{fill}" font-size="{size}" font-weight="{weight}" text-anchor="{anchor}">{escape(value)}</text>'


def line(x1, y, x2, colour, marker):
    return f'<path d="M{x1} {y} H{x2}" fill="none" stroke="{colour}" stroke-width="2.4" marker-end="url(#{marker})"/>'


def panel(x, y, width, height, item, mobile, prefix):
    parts = [rect(x, y, width, height, '#111827', '#52627a')]
    parts.append(text(x + 20, y + 33, item['name'], 19 if mobile else 18, INK, 650))
    parts.append(text(x + 20, y + 56, item['status'], 15 if mobile else 14, MUTED))
    node_y = y + 78
    node_w = 105 if mobile else 92
    right_x = x + width - 20 - node_w
    parts += [rect(x + 20, node_y, node_w, 45, '#0b0e14', AUDIO, 7),
              rect(right_x, node_y, node_w, 45, '#0b0e14', CLOCK, 7),
              text(x + 20 + node_w / 2, node_y + 29, 'SOURCE', 16 if mobile else 13, INK, 600, 'middle'),
              text(right_x + node_w / 2, node_y + 29, 'DAC', 16 if mobile else 13, INK, 600, 'middle')]
    first_y = y + 162
    step = 50 if mobile else 51
    for index, (label, direction, colour, bearing) in enumerate(item['lanes']):
        route_y = first_y + index * step
        parts.append(text(x + 20, route_y - 10, f'{label}: {direction}', 16 if mobile else 14, colour))
        x1, x2 = (x + 30, x + width - 30) if bearing == 'forward' else (x + width - 30, x + 30)
        marker = prefix + '-' + ('audio' if colour == AUDIO else 'control' if colour == CONTROL else 'clock')
        parts.append(line(x1, route_y + 7, x2, colour, marker))
    note_y = y + height - 56
    parts.append(text(x + 20, note_y, item['note'], 14 if mobile else 12.5, MUTED))
    parts.append(text(x + 20, y + height - 25, item['ports'], 15 if mobile else 13, INK, 600))
    return ''.join(parts)


def svg(mobile):
    prefix = 'o2at-compare-narrow' if mobile else 'o2at-compare-wide'
    width, height = (420, 1205) if mobile else (1080, 478)
    cards = [(20, 70 + 375 * i, 380, 365) for i in range(3)] if mobile else [(20 + 353 * i, 86, 333, 365) for i in range(3)]
    defs = ''.join(
        f'<marker id="{prefix}-{name}" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 1.5 L9 5 L0 8.5 Z" fill="{colour}"/></marker>'
        for name, colour in [('audio', AUDIO), ('control', CONTROL), ('clock', CLOCK)]
    )
    title = 'O2AT optical architecture comparison'
    description = ('Type 1 carries audio towards the DAC and receiver credits back on one duplex SFP. '
                   'Proposed Type 2A replaces the reverse path with a candidate coded reference, leaving runtime control to be defined. '
                   'Proposed Type 2B retains audio and return credits on port 1 and adds a forward optical reference on port 2.')
    content = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" preserveAspectRatio="xMidYMid meet" role="img" aria-labelledby="{prefix}-title {prefix}-desc" font-family="Avenir Next, Avenir, Inter, system-ui, sans-serif">',
               f'<title id="{prefix}-title">{title}</title><desc id="{prefix}-desc">{description}</desc>',
               f'<defs>{defs}</defs>', rect(0, 0, width, height, '#0b0e14', '#0b0e14', 10, 0),
               text(20, 35, 'Compare three optical paths' if mobile else 'One baseline, two proposed reference paths', 20 if mobile else 23, INK, 650)]
    if not mobile:
        content.append(text(20, 59, 'Audio, return control and reference use distinct signal roles.', 14, MUTED))
    for (x, y, w, h), item in zip(cards, PANELS):
        content.append(panel(x, y, w, h, item, mobile, prefix))
    content.append('</svg>')
    return ''.join(content)


for mobile in (False, True):
    filename = 'architecture-comparison-mobile.svg' if mobile else 'architecture-comparison.svg'
    (OUT / filename).write_text(svg(mobile) + '\n', encoding='utf-8')
    print(OUT / filename)
