import os, re, json, ctypes
from pathlib import Path
from functools import cmp_to_key

# ========= 排序逻辑 =========

if os.name == "nt":
    _strcmp = ctypes.windll.shlwapi.StrCmpLogicalW
    _strcmp.argtypes, _strcmp.restype = [ctypes.c_wchar_p, ctypes.c_wchar_p], ctypes.c_int
    def _cmp_name(a, b): return _strcmp(str(a), str(b))
else:
    def _alphanum_key(s): return [int(x) if x.isdigit() else x.lower() for x in re.split(r'(\d+)', s)]
    def _cmp_name(a, b):
        ka, kb = _alphanum_key(a), _alphanum_key(b)
        return (ka > kb) - (ka < kb)

# ========= 树构建 =========

def safe_stat(path):
    try:
        return os.stat(path, follow_symlinks=False)
    except Exception:
        return None

def scan_tree(path):
    """扫描目录并返回 [name, size或children, mtime]"""
    if os.path.islink(path):
        return None

    st = safe_stat(path)
    if not st:
        return None

    name = Path(path).name
    if os.path.isdir(path):
        try:
            entries = os.listdir(path)
        except OSError:
            return [name, [], int(st.st_mtime)]

        def cmp_entry(a, b):
            a_path, b_path = os.path.join(path, a), os.path.join(path, b)
            a_isdir, b_isdir = os.path.isdir(a_path), os.path.isdir(b_path)
            return -1 if a_isdir and not b_isdir else 1 if b_isdir and not a_isdir else _cmp_name(a, b)

        children = filter(None, (scan_tree(os.path.join(path, e)) for e in sorted(entries, key=cmp_to_key(cmp_entry))))
        return [name, list(children), int(st.st_mtime)]
    else:
        return [name, st.st_size, int(st.st_mtime)]

# ========= 主函数 =========

def main():
    root = "d"
    if not os.path.exists(root):
        print(f"Error: The directory '{root}' does not exist")
        return
    print("Scanning directory, please wait...")

    tree = scan_tree(root)
    if tree: tree[0] = ""  # 根名置空
    Path("static").mkdir(exist_ok=True)
    with open("static/data.json", "w", encoding="utf-8") as f:
        json.dump(tree, f, ensure_ascii=False, separators=(",", ":"))
    print("Data has been exported to static/data.json")

if __name__ == "__main__":
    main()