"""Draw a 32 x 32 pixel bow and export PNG plus a standalone HTML exporter.

Run: python cung_32x32.py
Requires Pillow: pip install pillow
"""

import json
from pathlib import Path

from PIL import Image, ImageDraw


OUT = Path(__file__).resolve().parent
SIZE = 32
PALETTE = {
    "outline": "#222537",
    "wood_shadow": "#73432c",
    "wood": "#bb713b",
    "wood_light": "#efb665",
    "gold_shadow": "#b77a36",
    "gold": "#edba58",
    "gold_light": "#ffe3a0",
    "string_shadow": "#746e75",
    "string": "#e8dfb9",
    "grip_shadow": "#14434d",
    "grip": "#287579",
    "grip_light": "#60b5a4",
    "steel_shadow": "#738d9f",
    "steel": "#b6d4db",
    "steel_light": "#edf6e7",
}


def draw_bow():
    """Draw directly at the target resolution: hard pixels, no antialiasing."""
    sprite = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
    d = ImageDraw.Draw(sprite)
    c = PALETTE

    # The taut bowstring sits behind the wooden limbs and the arrow.
    d.line([(12, 3), (6, 15), (12, 28)], fill=c["outline"], width=3)
    d.line([(12, 3), (6, 15), (12, 28)], fill=c["string"], width=1)
    d.point((7, 15), fill=c["string_shadow"])

    # Curved wooden limbs, with an outer outline and hand-placed highlights.
    curve = [(11, 2), (12, 4), (15, 6), (17, 8), (18, 11),
             (20, 13), (20, 18), (18, 20), (17, 23), (15, 25),
             (12, 27), (11, 29)]
    d.line(curve, fill=c["outline"], width=5, joint="curve")
    d.line(curve, fill=c["wood_shadow"], width=3, joint="curve")
    d.line([(11, 3), (12, 4), (15, 6), (17, 8), (18, 11), (20, 14)],
           fill=c["wood"], width=2)
    d.line([(20, 17), (18, 20), (17, 23), (15, 25), (12, 27), (11, 28)],
           fill=c["wood"], width=2)
    d.line([(11, 3), (12, 4), (15, 6), (16, 8), (17, 10)],
           fill=c["wood_light"], width=1)
    d.line([(19, 19), (17, 22), (16, 24), (14, 25), (12, 27)],
           fill=c["wood_light"], width=1)

    # Brass tips and teal wrapped grip.
    for tip_y in (1, 27):
        d.rectangle((10, tip_y, 13, tip_y + 3), fill=c["outline"])
        d.rectangle((11, tip_y, 12, tip_y + 2), fill=c["gold"])
        d.point((11, tip_y), fill=c["gold_light"])
        d.point((12, tip_y + 2), fill=c["gold_shadow"])
    d.rectangle((18, 12, 22, 19), fill=c["outline"])
    d.rectangle((19, 13, 21, 18), fill=c["grip_shadow"])
    for y in (13, 15, 17):
        d.line((19, y, 21, y + 1), fill=c["grip"], width=1)
        d.point((19, y), fill=c["grip_light"])
    for y in (12, 19):
        d.line((19, y, 21, y), fill=c["gold"], width=1)

    # A right-pointing arrow, with teal feathers and a steel arrowhead.
    d.line((3, 15, 28, 15), fill=c["outline"], width=3)
    d.line((4, 15, 27, 15), fill=c["wood_light"], width=1)
    d.line((8, 16, 25, 16), fill=c["wood_shadow"], width=1)
    d.polygon([(2, 11), (5, 11), (8, 14), (8, 16), (5, 19),
               (2, 19), (4, 15)], fill=c["outline"])
    d.polygon([(3, 12), (5, 12), (7, 14), (5, 14)], fill=c["grip_light"])
    d.polygon([(5, 16), (7, 16), (5, 18), (3, 18)], fill=c["grip"])
    d.line((3, 15, 8, 15), fill=c["wood_light"])
    d.polygon([(25, 11), (30, 15), (25, 19), (25, 17),
               (24, 17), (24, 13), (25, 13)], fill=c["outline"])
    d.polygon([(26, 13), (29, 15), (26, 17)], fill=c["steel"])
    d.line((26, 13, 28, 15), fill=c["steel_light"])
    d.line((26, 17, 28, 16), fill=c["steel_shadow"])
    d.point((25, 15), fill=c["steel"])
    return sprite


def export_html(sprite):
    """Embed the exact pixel data in a browser-only, editable Canvas example."""
    palette = ["transparent"]
    lookup = {(0, 0, 0, 0): 0}
    rows = []
    for y in range(SIZE):
        row = []
        for x in range(SIZE):
            color = sprite.getpixel((x, y))
            if color not in lookup:
                lookup[color] = len(palette)
                palette.append("#%02x%02x%02x" % color[:3])
            row.append(lookup[color])
        rows.append(row)
    html = """<!doctype html>
<html lang="vi">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cung pixel art 32×32</title>
<style>
  * { box-sizing: border-box; }
  body { margin:0; min-height:100vh; padding:24px; display:grid;
    place-items:center; background:#151a25; color:#f5eedb;
    font:16px/1.5 system-ui,sans-serif; }
  main { text-align:center; max-width:100%; }
  h1 { font-size:24px; margin:0 0 8px; }
  p { color:#b9c1cf; margin:0 0 20px; }
  .preview { width:min(320px,80vw); aspect-ratio:1; margin:0 auto 24px;
    border:1px solid #3b4354; border-radius:12px; overflow:hidden;
    background-color:#252d3a;
    background-image:conic-gradient(#303a49 25%,transparent 0 50%,#303a49 0 75%,transparent 0);
    background-size:40px 40px; }
  canvas { width:100%; height:100%; image-rendering:pixelated; display:block; }
  button { font:inherit; font-weight:650; color:#152c30; background:#7ed8bd;
    border:0; padding:12px 24px; border-radius:8px; cursor:pointer; }
  button:hover { background:#a0ead3; }
  button:focus-visible { outline:3px solid #ffe3a0; outline-offset:4px; }
  small { display:block; margin-top:12px; color:#b9c1cf; }
</style>
<main>
  <h1>Cung pixel art</h1>
  <p>32 × 32 pixel · PNG nền trong suốt</p>
  <div class="preview"><canvas id="bow" width="32" height="32"
    role="img" aria-label="Cây cung gỗ với dây cung và mũi tên"></canvas></div>
  <button id="download" type="button">Tải PNG 32×32</button>
  <small>Ảnh xem trước phóng to 10 lần.</small>
</main>
<script>
// Sửa bảng màu hoặc các ô trong pixels để thay đổi hình.
const palette = __PALETTE__;
const pixels = __PIXELS__;
const canvas = document.getElementById('bow');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
pixels.forEach((row, y) => row.forEach((color, x) => {
  if (!color) return;
  ctx.fillStyle = palette[color];
  ctx.fillRect(x, y, 1, 1);
}));
document.getElementById('download').addEventListener('click', () => {
  const link = document.createElement('a');
  link.download = 'cung_32x32.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
});
</script>
</html>
"""
    pixel_json = "[\n" + ",\n".join("  " + json.dumps(row) for row in rows) + "\n]"
    html = html.replace("__PALETTE__", json.dumps(palette))
    html = html.replace("__PIXELS__", pixel_json)
    (OUT / "cung_32x32.html").write_text(html, encoding="utf-8")


def main():
    sprite = draw_bow()
    sprite.save(OUT / "cung_32x32.png")
    export_html(sprite)
    # Separate enlarged preview; the exported sprite stays exactly 32 x 32.
    enlarged = sprite.resize((320, 320), Image.Resampling.NEAREST)
    backdrop = Image.new("RGBA", enlarged.size, "#252d3a")
    cells = ImageDraw.Draw(backdrop)
    for y in range(0, 320, 20):
        for x in range(0, 320, 20):
            if (x // 20 + y // 20) % 2:
                cells.rectangle((x, y, x + 19, y + 19), fill="#303a49")
    backdrop.alpha_composite(enlarged)
    backdrop.convert("RGB").save(OUT / "cung_preview.png")
    with Image.open(OUT / "cung_32x32.png") as result:
        assert result.size == (32, 32)
        assert result.mode == "RGBA"
        assert set(result.getchannel("A").getdata()) == {0, 255}
    print(f"PNG: {OUT / 'cung_32x32.png'} (32 x 32, RGBA)")
    print(f"HTML: {OUT / 'cung_32x32.html'}")


if __name__ == "__main__":
    main()
