#!/usr/bin/env python3
"""
将 brand/icons 同步到中控与各所 static/icons(Chrome 快捷方式 / 标签页图标).

用法(仓库根目录):
  python scripts/generate_brand_icons.py
  python scripts/sync_brand_icons.py
"""
from __future__ import annotations

import os
import shutil

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(REPO, "brand", "icons")

HUB_DEST = os.path.join(REPO, "manual_trading_hub", "static", "icons")
EXCHANGES = (
    ("crypto_monitor_binance", "binance", "manifest.binance.webmanifest"),
    ("crypto_monitor_okx", "okx", "manifest.okx.webmanifest"),
    ("crypto_monitor_gate", "gate", "manifest.gate.webmanifest"),
)

FILES = (
    "icon.svg",
    "favicon.ico",
    "icon-16.png",
    "icon-32.png",
    "icon-192.png",
    "icon-512.png",
    "apple-touch-icon.png",
)


def sync_dir(src_dir: str, dest: str, url_prefix: str, manifest_template: str) -> str:
    if not os.path.isdir(src_dir):
        return f"SKIP {dest}: 缺少 {src_dir},请先运行 python scripts/generate_brand_icons.py"
    os.makedirs(dest, exist_ok=True)
    for name in FILES:
        src = os.path.join(src_dir, name)
        if not os.path.isfile(src):
            return f"SKIP {dest}: 缺少 {src}"
        shutil.copy2(src, os.path.join(dest, name))
    manifest_src = os.path.join(REPO, "brand", manifest_template)
    if os.path.isfile(manifest_src):
        with open(manifest_src, encoding="utf-8") as f:
            text = f.read().replace("__ICON_PREFIX__", url_prefix)
        with open(
            os.path.join(dest, "manifest.webmanifest"),
            "w",
            encoding="utf-8",
            newline="\n",
        ) as f:
            f.write(text)
    return f"DONE {dest}"


def main() -> None:
    print(sync_dir(SRC, HUB_DEST, "/assets/icons", "manifest.webmanifest"))
    for folder, key, manifest in EXCHANGES:
        dest = os.path.join(REPO, folder, "static", "icons")
        src_dir = os.path.join(SRC, key)
        print(sync_dir(src_dir, dest, "/static/icons", manifest))


if __name__ == "__main__":
    main()
