"""Ve cung pixel 32x32 va xuat PNG trong suot.

Chay: pip install Pillow
      python tao_cung.py
Mo cung_32x32.html de xem va tai PNG bang trinh duyet.
"""

from pathlib import Path
import json

from PIL import Image, ImageDraw, ImageFilter


SIZE = 32
OUT = Path(__file__).resolve().parent
COLORS = {
    "outline": "#2b2230",
    "wood_shadow": "#74402f",
    "wood": "#b96d38",
    "wood_light": "#edb461",
    "wood_glint": "#ffe3a0",
    "string_shadow": "#84766b",
    "string": "#eadfc2",
    "grip_shadow": "#28323c",
    "grip": "#49566a",
    "grip_light": "#81939c",
    "gold_shadow": "#a76a31",
    "gold": "#e9b54e",
    "gold_light": "#ffe69a",
}


def make_bow():
    im = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
    d = ImageDraw.Draw(im)

    # Day cung: hai duong mot pixel, khong khu rang cua.
    d.line([(5, 8), (22, 27)], fill=COLORS["string_shadow"])
    d.line([(4, 8), (21, 27)], fill=COLORS["string"])

    # Hai canh cung lien mach; vien dam rong dung mot pixel.
    body = [
        (4, 7), (7, 5), (10, 4), (14, 4), (18, 5),
        (21, 7), (24, 10), (26, 14), (27, 18), (27, 21),
        (26, 24), (24, 27), (22, 28), (21, 27),
        (23, 24), (24, 21), (24, 18), (23, 15),
        (21, 12), (18, 9), (15, 8), (12, 7), (9, 7),
        (6, 9), (4, 9),
    ]
    mask = Image.new("L", (SIZE, SIZE), 0)
    ImageDraw.Draw(mask).polygon(body, fill=255)
    outline = mask.filter(ImageFilter.MaxFilter(3))
    im.paste(COLORS["outline"], (0, 0), outline)
    im.paste(COLORS["wood_shadow"], (0, 0), mask)
    d = ImageDraw.Draw(im)
    d.line([(5, 7), (8, 6), (11, 5), (14, 5), (18, 6),
            (21, 8), (23, 10), (25, 14), (26, 18),
            (26, 21), (25, 24), (23, 27)],
           fill=COLORS["wood"], width=2)
    d.line([(6, 6), (10, 5), (14, 5), (17, 6), (20, 8)],
           fill=COLORS["wood_light"])
    d.line([(25, 16), (26, 19), (26, 21), (25, 23), (23, 26)],
           fill=COLORS["wood_light"])
    d.line([(10, 5), (13, 5)], fill=COLORS["wood_glint"])

    # Tay cam boc da xanh xam, nam cheo theo than cung.
    grip = [(20, 7), (23, 9), (25, 12), (23, 14),
            (21, 12), (18, 9)]
    d.polygon(grip, fill=COLORS["grip_shadow"])
    d.line([(20, 8), (22, 10), (24, 12)],
           fill=COLORS["grip"], width=2)
    for start, end in [((19, 9), (21, 8)),
                       ((21, 11), (23, 10)),
                       ((23, 13), (24, 12))]:
        d.line([start, end], fill=COLORS["grip_light"])

    # Hai dai dong va dau cung vang.
    for a, b in [((17, 8), (19, 6)), ((24, 15), (26, 13))]:
        d.line([a, b], fill=COLORS["gold_shadow"], width=2)
        d.line([a, b], fill=COLORS["gold"])
        d.point(b, fill=COLORS["gold_light"])
    d.line([(4, 7), (5, 8)], fill=COLORS["gold"], width=2)
    d.point((4, 7), fill=COLORS["gold_light"])
    d.line([(21, 27), (22, 28)], fill=COLORS["gold"], width=2)
    d.point((21, 27), fill=COLORS["gold_light"])
    return im


def make_html(im):
    # Canvas dung kich thuoc that 32x32. CSS chi phong to phan xem truoc.
    pixels = json.dumps(list(im.getdata()), separators=(",", ":"))
    page = '''<!doctype html>
<html lang="vi">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cung pixel 32 × 32</title>
<style>
*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;
background:#171b23;color:#f3ead8;font:16px system-ui,sans-serif}
main{text-align:center;padding:32px}h1{font-size:26px;margin:0 0 8px}
p{color:#b8bfca;margin:0 0 24px}canvas{display:block;width:min(80vw,384px);
height:auto;image-rendering:pixelated;border-radius:8px;
background:conic-gradient(#2c3340 25%,#242b36 0 50%,#2c3340 0 75%,#242b36 0);
background-size:24px 24px;margin:0 auto 24px}
button{border:0;border-radius:10px;padding:13px 24px;background:#e9b54e;color:#201b15;
font:600 16px system-ui;cursor:pointer}button:hover{background:#ffe69a}
button:focus-visible{outline:3px solid white;outline-offset:4px}
</style>
<main><h1>Cung pixel 32 × 32</h1>
<p>Nền trong suốt · PNG · Vẽ bằng code</p>
<canvas id="bow" width="32" height="32" aria-label="Cây cung gỗ pixel art, tay cầm bọc da xanh xám"></canvas>
<button id="save">Tải PNG 32 × 32</button></main>
<script>
const pixels = PIXEL_DATA;
const canvas = document.getElementById('bow');
const context = canvas.getContext('2d');
context.imageSmoothingEnabled = false;
context.putImageData(new ImageData(new Uint8ClampedArray(pixels.flat()),32,32),0,0);
document.getElementById('save').addEventListener('click',()=>{
  const link=document.createElement('a');
  link.download='cung_32x32.png';
  link.href=canvas.toDataURL('image/png');
  link.click();
});
</script>
</html>
'''.replace("PIXEL_DATA", pixels)
    (OUT / "cung_32x32.html").write_text(page, encoding="utf-8")


if __name__ == "__main__":
    bow = make_bow()
    bow.save(OUT / "cung_32x32.png")
    bow.resize((512, 512), Image.Resampling.NEAREST).save(OUT / "xem_truoc_512.png")
    make_html(bow)
    with Image.open(OUT / "cung_32x32.png") as exported:
        assert exported.size == (32, 32)
        assert exported.mode == "RGBA"
        assert set(exported.getchannel("A").getdata()) == {0, 255}
    print(f"Da xuat PNG 32x32 RGBA, nen trong suot: {OUT}")
