#!/usr/bin/env python3
"""从 Unity 源按 sanxing 命名规范完整同步主题贴图。"""
from __future__ import annotations

import importlib.util
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TEX = ROOT / "assets" / "resources" / "textures"
UNITY = Path("/Users/liuyufei/tfrh/竞赛/scratch-unity-base/Assets/Texture")

_spec = importlib.util.spec_from_file_location(
    "unify", ROOT / "tools" / "unify-theme-texture-names.py"
)
unify = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(unify)

RENAMES = unify.RENAMES
THEME_SHIP = unify.THEME_SHIP


def unity_src(theme: str, rel: str) -> Path | None:
    rel = rel.replace(".png", "")

    def with_png(base: Path) -> Path | None:
        fp = base.with_suffix(".png")
        return fp if fp.exists() else None

    if theme == "chinese":
        if rel.startswith("skin/"):
            hit = with_png(UNITY / "Panda" / rel[len("skin/"):])
            if hit:
                return hit
        hit = with_png(UNITY / "Chinese" / rel)
        if hit:
            return hit
        return with_png(TEX / "chinese" / "_legacy" / rel)
    if theme == "redArmy":
        rel_u = rel.replace("redArmyShip", "redarmyship")
        return with_png(UNITY / "redarmy" / rel_u)
    p = UNITY / theme / rel
    if theme == "silu" and not p.with_suffix(".png").exists() and rel.startswith("skin/跳背面/"):
        name = Path(rel).name
        alt_name = "机器人" if name == "1" else f"机器人{name}"
        hit = with_png(UNITY / "silu" / "player" / "jump-正" / alt_name)
        if hit:
            return hit
    return with_png(p)


def cocos_dst(theme: str, rel: str) -> Path:
    return (TEX / theme / rel.replace(".png", "")).with_suffix(".png")


def sync_theme(theme: str) -> int:
    copied = 0
    for t, old_rel, new_rel in RENAMES:
        if t != theme:
            continue
        src = unity_src(theme, old_rel)
        if not src:
            continue
        dst = cocos_dst(theme, new_rel)
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)
        copied += 1
    # 已有 sanxing 命名的根目录文件（Unity 与 sanxing 同名）
    if theme == "numMan":
        src = UNITY / "numMan" / "nProp_kuai .png"
        if src.exists():
            shutil.copy2(src, TEX / "numMan" / "nProp_kuai1.png")
            copied += 1
        for name in [
            "Baseblock", "JumpBlock", "WallBlock", "kuai11", "bg",
            "anniu_03", "anniu_06", "anniu_08", "anniu_10", "anniu_12",
            "anniu_17", "anniu_19", "anniu_21", "anniu_22",
        ]:
            src = UNITY / "numMan" / f"{name}.png"
            if src.exists():
                shutil.copy2(src, TEX / "numMan" / f"{name}.png")
                copied += 1
        sf, sb = THEME_SHIP["numMan"]
        for name in (sf, sb):
            src = UNITY / "numMan" / f"{name}.png"
            if src.exists():
                shutil.copy2(src, TEX / "numMan" / f"{name}.png")
                copied += 1
    if theme == "redArmy":
        for name in [
            "Baseblock", "JumpBlock", "WallBlock", "bg",
        ]:
            src = UNITY / "redarmy" / f"{name}.png"
            if src.exists():
                shutil.copy2(src, TEX / "redArmy" / f"{name}.png")
                copied += 1
    if theme == "snow":
        for old, new in [("Prop_kuai2", "Prop_kuai1"), ("nProp_kuai2", "nProp_kuai1")]:
            for base in [TEX / "snow", TEX / "snow" / "_legacy", TEX / "_orphan_stages" / "snow"]:
                src = base / f"{old}.png"
                if src.exists():
                    shutil.copy2(src, TEX / "snow" / f"{new}.png")
                    copied += 1
                    break
    return copied


def main() -> None:
    total = 0
    for theme in ["silu", "numMan", "redArmy", "chinese", "snow"]:
        n = sync_theme(theme)
        print(f"{theme}: copied {n}")
        total += n
    unify.patch_themes_database()
    unify.patch_palettes()
    print(f"done, {total} files")


if __name__ == "__main__":
    main()
