# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (c) 2026 sol pbc

"""Generate the browser-side Convey icon accessor from vendored Lucide data."""

from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Mapping

LOGGER = logging.getLogger(__name__)

CONVEY_ICON_NAMES: tuple[str, ...] = (
    "activity",
    "alarm-clock",
    "audio-lines",
    "bell",
    "bell-off",
    "bot",
    "brain",
    "calendar-days",
    "chart-column",
    "check",
    "circle-check",
    "circle-x",
    "clock",
    "coins",
    "eye",
    "file-text",
    "inbox",
    "life-buoy",
    "lock",
    "mailbox",
    "mic-vocal",
    "monitor",
    "mouse-pointer-2",
    "refresh-cw",
    "satellite-dish",
    "search",
    "sparkles",
    "tag",
    "timer",
    "trash-2",
    "triangle-alert",
    "undo-2",
    "users",
    "volume-2",
    "wrench",
    "zap",
)

REPO_ROOT = Path(__file__).resolve().parents[1]
LUCIDE_JSON_PATH = (
    REPO_ROOT / "solstone" / "convey" / "static" / "icons" / "lucide.json"
)
OUTPUT_PATH = REPO_ROOT / "solstone" / "convey" / "static" / "convey_icons.js"


def load_lucide_icons(path: Path = LUCIDE_JSON_PATH) -> dict[str, str]:
    return json.loads(path.read_text(encoding="utf-8"))


def selected_icons(
    lucide_icons: Mapping[str, str],
    names: tuple[str, ...] = CONVEY_ICON_NAMES,
) -> dict[str, str]:
    missing = [name for name in names if name not in lucide_icons]
    if missing:
        raise KeyError("missing Lucide icon(s): " + ", ".join(missing))
    return {name: lucide_icons[name] for name in names}


def render_convey_icons_js(icons: Mapping[str, str]) -> str:
    payload = json.dumps(dict(icons), ensure_ascii=False, indent=2)
    return (
        "// SPDX-License-Identifier: AGPL-3.0-only\n"
        "// Copyright (c) 2026 sol pbc\n"
        "\n"
        "// Generated by scripts/build_convey_icons.py. Do not edit by hand.\n"
        "(function () {\n"
        "  const ICONS = Object.freeze(" + payload.replace("\n", "\n  ") + ");\n"
        "\n"
        "  function svg(name) {\n"
        "    if (!Object.prototype.hasOwnProperty.call(ICONS, name)) return '';\n"
        "    return ICONS[name];\n"
        "  }\n"
        "\n"
        "  window.ConveyIcons = Object.freeze({ svg });\n"
        "})();\n"
    )


def write_convey_icons(output_path: Path = OUTPUT_PATH) -> None:
    js = render_convey_icons_js(selected_icons(load_lucide_icons()))
    output_path.write_text(js, encoding="utf-8")
    LOGGER.info("wrote %s", output_path)


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    write_convey_icons()
    return 0


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