"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = spriteBrowseRoutes;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("@yinuo-ngm/errors");
const SKIP = new Set([
    ".svn",
    ".git",
    ".hg",
    ".DS_Store",
    "__MACOSX",
    "Thumbs.db",
]);
function safeJoin(root, sub) {
    const resolved = node_path_1.default.resolve(root, sub);
    const rootResolved = node_path_1.default.resolve(root);
    if (!resolved.startsWith(rootResolved)) {
        throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "INVALID_PATH");
    }
    return resolved;
}
function listDir(root) {
    if (!node_fs_1.default.existsSync(root))
        return [];
    return node_fs_1.default
        .readdirSync(root, { withFileTypes: true })
        .filter(d => !SKIP.has(d.name) && !d.name.startsWith("."))
        .map(d => ({
        name: d.name,
        kind: d.isDirectory() ? "dir" : "file",
        ext: d.isDirectory() ? undefined : node_path_1.default.extname(d.name).toLowerCase(),
    })).sort((a, b) => {
        if (a.kind === b.kind) {
            return a.name.localeCompare(b.name, "zh-Hans-CN", { numeric: true });
        }
        return a.kind === "dir" ? -1 : 1;
    });
}
function countFiles(dir) {
    if (!node_fs_1.default.existsSync(dir) || !node_fs_1.default.statSync(dir).isDirectory())
        return 0;
    return node_fs_1.default.readdirSync(dir, { withFileTypes: true }).filter(d => d.isFile()).length;
}
async function spriteBrowseRoutes(fastify) {
    fastify.get("/icons/groups/:projectId", async (req) => {
        const { projectId } = req.params;
        const project = await fastify.core.project.get(projectId);
        const cfg = await fastify.core.sprite.getConfig(projectId);
        const localRoot = String(cfg?.localImageRoot ?? "").trim();
        const root = localRoot || project?.assets?.iconsSvn?.localDir;
        if (!root) {
            return { root: "", entries: [] };
        }
        const entries = listDir(root).filter(e => e.kind === "dir");
        if (localRoot) {
            const rootFiles = listDir(root).filter((e) => e.kind === "file" && (e.ext === ".png" || e.ext === ".svg"));
            if (rootFiles.length > 0) {
                entries.unshift({ name: "root", kind: "dir", ext: undefined });
            }
        }
        return { root, entries };
    });
    fastify.get("/icons/files/:projectId", async (req) => {
        const { projectId } = req.params;
        const group = req.query?.group;
        const project = await fastify.core.project.get(projectId);
        const cfg = await fastify.core.sprite.getConfig(projectId);
        const localRoot = String(cfg?.localImageRoot ?? "").trim();
        const root = localRoot || project?.assets?.iconsSvn?.localDir;
        if (!root) {
            return { root: "", entries: [] };
        }
        const isRootGroup = !!localRoot && (group === "root");
        const groupDir = isRootGroup ? root : safeJoin(root, group || '');
        const entries = listDir(groupDir)
            .filter(e => e.kind === "file")
            .map(e => ({
            ...e,
            url: localRoot
                ? `/api/static/local/${projectId}/${isRootGroup ? e.name : `${group}/${e.name}`}`
                : `/api/static/svn/${projectId}/icons/${group}/${e.name}`,
        }));
        return { root: groupDir, entries };
    });
    fastify.get("/images/list/:projectId", async (req) => {
        const { projectId } = req.params;
        const project = await fastify.core.project.get(projectId);
        const root = project?.assets?.cutImageSvn?.localDir;
        if (!root) {
            return { root: "", entries: [] };
        }
        const dir = String(req.query?.dir ?? "").trim();
        if (dir.split(/[\\/]/g).some(seg => seg === "..")) {
            return { root, dir: "", entries: [] };
        }
        const absDir = dir ? safeJoin(root, dir) : root;
        if (!node_fs_1.default.existsSync(absDir))
            return { root, dir, entries: [] };
        const entries = listDir(absDir).map(e => {
            if (e.kind === "file") {
                const rel = dir ? `${dir}/${e.name}` : e.name;
                return {
                    ...e,
                    url: `/api/static/svn/${projectId}/images/${rel}`,
                };
            }
            else if (e.kind === "dir") {
                const rel = dir ? `${dir}/${e.name}` : e.name;
                return {
                    ...e,
                    fileCount: countFiles(safeJoin(root, rel))
                };
            }
            return e;
        });
        return { root, dir, entries };
    });
}
