#!/usr/bin/env python3
from __future__ import annotations

import struct
import sys
from pathlib import Path


PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: generate_ico_from_png.py <input.png> <output.ico>", file=sys.stderr)
        return 1

    source = Path(sys.argv[1])
    target = Path(sys.argv[2])

    png = source.read_bytes()
    if not png.startswith(PNG_SIGNATURE):
        print(f"{source} is not a PNG file", file=sys.stderr)
        return 1

    width = int.from_bytes(png[16:20], "big")
    height = int.from_bytes(png[20:24], "big")
    width_byte = 0 if width >= 256 else width
    height_byte = 0 if height >= 256 else height

    header = struct.pack("<HHH", 0, 1, 1)
    directory = struct.pack(
        "<BBBBHHII",
        width_byte,
        height_byte,
        0,
        0,
        1,
        32,
        len(png),
        len(header) + 16,
    )

    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_bytes(header + directory + png)
    print(f"wrote {target}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
