"""Single-line branded SVG for an equation under a bar model.

Used by `solution_block.py`, also usable standalone (one equation per call).
The `algebra` field is recorded on the data side so the future P5–P6 algebra
toggle can re-render the same step as an algebraic equation without a retrofit.

generate(text, *, algebra=None, width=860, height=44, emphasize=False) -> str
"""

STYLE = (
    "<style>svg{--crimson:#960000;--gold:#BF9237;--lime:#88C808;"
    "--steel:#4A6488;--cream:#FAF5EE;--ink:#2A2A2A;--border:#D0ACAC;}</style>"
)


def _esc(s):
    return (str(s).replace('&', '&amp;').replace('<', '&lt;')
            .replace('>', '&gt;'))


def generate(text, *, algebra=None, width=860, height=44,
             emphasize=False, border=True):
    """Render one equation line as SVG.

    `algebra` is captured (data-only) but not yet rendered — it carries the
    algebraic form of `text` for a future toggle. e.g. text="1 unit = 4",
    algebra="u = 4".
    """
    fill = 'var(--crimson)' if emphasize else 'var(--ink)'
    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" '
        f'height="{height}" viewBox="0 0 {width} {height}" '
        f'data-algebra="{_esc(algebra) if algebra else ""}">',
        STYLE,
    ]
    if border:
        parts.append(
            f'<rect x="3" y="3" width="{width-6}" height="{height-6}" rx="6" '
            f'fill="none" stroke="var(--border)" stroke-width="2"/>'
        )
    parts.append(
        f'<text x="{width/2}" y="{height/2}" font-family="sans-serif" '
        f'font-size="17" font-weight="bold" fill="{fill}" '
        f'text-anchor="middle" dominant-baseline="central">{_esc(text)}</text>'
    )
    parts.append('</svg>')
    return '\n'.join(parts)


if __name__ == '__main__':
    import os
    out = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'samples'))
    os.makedirs(out, exist_ok=True)
    s = generate(
        "Number of teddy bears Jenny has = 8 + 10 = 18",
        algebra="J = S + 10 = 8 + 10 = 18",
    )
    with open(os.path.join(out, 'equation_line.svg'), 'w',
              encoding='utf-8') as f:
        f.write(s)
    print('wrote equation_line.svg')
