#!/usr/bin/env python3
"""Render an editable vector swatch sheet from the authoritative JSON values.

The patterns are schematic SVG illustrations, not baked PBR textures or rendered material proof.
"""
from html import escape
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def render() -> str:
    data = json.loads((ROOT / "material_library.json").read_text())
    rows = (len(data["materials"]) + 3) // 4
    width, height = 1480, 180 + rows * 250
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">',
           '<title id="title">Crown Key proposed material starter kit R01</title>',
           '<desc id="desc">Thirteen editable vector swatches with sRGB colors and proposed PBR values. Schematic patterns are not textures or material renders.</desc>',
           '<rect width="100%" height="100%" fill="#F3F0E8"/>',
           '<g font-family="Arial, sans-serif" fill="#132C34">',
           '<text x="40" y="52" font-size="31" font-weight="700">CROWN KEY / MATERIAL STARTER R01</text>',
           '<text x="40" y="84" font-size="17">Split Complex + Terrace Tower · proposed values · no engine acceptance</text>',
           '<text x="40" y="111" font-size="14">sRGB base-color chips; schematic vector patterns. Read material_library.json for linear shader values, UVs and provenance.</text>']
    for index, material in enumerate(data["materials"]):
        x, y = 40 + (index % 4) * 360, 140 + (index // 4) * 250
        color = material["base_color"]["srgb_hex"]
        pattern = f'pattern_{index + 1:02d}'
        marks = ''
        if material["normal"]["procedural_bump_distance_m"] > 0:
            marks = '<circle cx="5" cy="7" r="1" fill="#182D2E" opacity="0.16"/><circle cx="17" cy="15" r="0.8" fill="#FFFFFF" opacity="0.35"/>'
        if 'TIMBER' in material["id"]:
            marks = '<path d="M0 4 Q10 2 24 6 M0 14 Q12 18 24 13" stroke="#3D281A" opacity="0.23" fill="none" stroke-width="1"/>'
        if 'LINEN' in material["id"]:
            marks = '<path d="M0 8 H24 M0 16 H24 M8 0 V24 M16 0 V24" stroke="#615A49" opacity="0.16" stroke-width="0.7"/>'
        out.append(f'<defs><pattern id="{pattern}" width="24" height="24" patternUnits="userSpaceOnUse"><rect width="24" height="24" fill="{color}"/>{marks}</pattern></defs>')
        out.append(f'<g id="{escape(material["id"])}" transform="translate({x},{y})">')
        out.append(f'<rect width="340" height="226" rx="8" fill="#FFFFFF" stroke="#D1D1C5"/>')
        out.append(f'<rect x="12" y="12" width="316" height="108" rx="5" fill="url(#{pattern})"/>')
        if material["transmission_weight"]:
            out.append('<path d="M30 100 L170 22 M130 110 L280 22" stroke="#FFFFFF" stroke-width="7" opacity="0.65"/>')
        out.append(f'<text x="14" y="145" font-size="18" font-weight="700">{index+1:02d} · {escape(material["name"])}</text>')
        out.append(f'<text x="14" y="168" font-size="13">sRGB {color}   R {material["roughness"]:.3f}   M {material["metallic"]:.1f}</text>')
        tile = material["uv"]["tile_size_m"]
        line = f'Tile {tile[0]:g} × {tile[1]:g} m · 1024 px proposal' if tile else 'Analytic shader · no texture map delivered'
        out.append(f'<text x="14" y="190" font-size="12">{escape(line)}</text>')
        note = 'Transmission 1 · IOR 1.5 · alpha 1' if material["transmission_weight"] else 'Unitless preview emission; not photometric' if "emission" in material else 'Edit JSON, then regenerate this SVG'
        out.append(f'<text x="14" y="211" font-size="11" fill="#5D696C">{escape(note)}</text></g>')
    out.append(f'<text x="40" y="{height - 16}" font-size="12">Source-backed palette direction; all numeric PBR, UV and budget values are proposed. No texture scan, baked map or engine rendering is claimed.</text></g></svg>')
    return '\n'.join(out) + '\n'


if __name__ == "__main__":
    output = ROOT / "swatch_sheet.svg"
    output.write_text(render())
    print(output.name)
