#!/usr/bin/env python3
"""从载具 F/B 贴图生成四向 N/E/S/W 资源（E/W 为 F/B 水平镜像，N/S 复制 B/F）。"""
from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TEX = ROOT / "assets" / "resources" / "textures"

# theme folder -> ship 文件名前缀（不含 _F/_B）
THEMES: dict[str, str] = {
    "silu": "siluShip",
    "sanxing": "sanxingShip",
    "snow": "snowShip",
    "chinese": "chineseShip",
    "numMan": "numManShip",
    "redArmy": "redArmyShip",
}


def flip_horizontal(src: Path, dst: Path) -> None:
    dst.parent.mkdir(parents=True, exist_ok=True)
    try:
        subprocess.run(
            ["sips", "-f", "horizontal", str(src), "--out", str(dst)],
            check=True,
            capture_output=True,
        )
    except (subprocess.CalledProcessError, FileNotFoundError):
        try:
            from PIL import Image
            Image.open(src).transpose(Image.FLIP_LEFT_RIGHT).save(dst)
        except ImportError as e:
            raise SystemExit(
                "需要 macOS sips 或 pip install Pillow 才能生成 E/W 镜像贴图"
            ) from e


def copy_meta(src_meta: Path, dst_meta: Path) -> None:
    if src_meta.is_file():
        shutil.copy2(src_meta, dst_meta)


def generate_for_theme(folder: str, prefix: str) -> None:
    base = TEX / folder
    f_png = base / f"{prefix}_F.png"
    b_png = base / f"{prefix}_B.png"
    if not f_png.is_file() or not b_png.is_file():
        print(f"  skip {folder}: missing {prefix}_F/_B")
        return

    n_png = base / f"{prefix}_N.png"
    s_png = base / f"{prefix}_S.png"
    e_png = base / f"{prefix}_E.png"
    w_png = base / f"{prefix}_W.png"

    shutil.copy2(b_png, n_png)
    shutil.copy2(f_png, s_png)
    flip_horizontal(f_png, e_png)
    flip_horizontal(b_png, w_png)

    copy_meta(b_png.with_suffix(".png.meta"), n_png.with_suffix(".png.meta"))
    copy_meta(f_png.with_suffix(".png.meta"), s_png.with_suffix(".png.meta"))
    copy_meta(f_png.with_suffix(".png.meta"), e_png.with_suffix(".png.meta"))
    copy_meta(b_png.with_suffix(".png.meta"), w_png.with_suffix(".png.meta"))

    print(f"  ok {folder}: {prefix}_{{N,E,S,W}}.png")


def main() -> int:
    print(f"textures root: {TEX}")
    for folder, prefix in THEMES.items():
        generate_for_theme(folder, prefix)
    print("done — 请在 Creator 中刷新 assets/resources/textures")
    return 0


if __name__ == "__main__":
    sys.exit(main())
