import { n as resolveSealseekApiContext, t as createSealseekShareClient } from "./sealseek-share-client-CN4eoXzW.js";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import JSZip from "jszip";
//#region src/infra/sealseek-install-skill-zip.ts
async function installSkillZip(params) {
	const targetDir = path.resolve(params.skillsRoot, params.skillName);
	const zip = await JSZip.loadAsync(params.zipBuffer);
	const entries = Object.values(zip.files);
	for (const entry of entries) {
		if (entry.dir) continue;
		const dest = path.resolve(targetDir, entry.name);
		if (dest !== targetDir && !dest.startsWith(targetDir + path.sep)) throw new Error(`非法压缩包路径(traversal): ${entry.name}`);
		mkdirSync(path.dirname(dest), { recursive: true });
		writeFileSync(dest, await entry.async("nodebuffer"));
	}
	return targetDir;
}
//#endregion
//#region src/commands/skill-share-import.ts
async function runSkillImport(codeOrUrl, deps) {
	const log = deps.log ?? console.log;
	const shareCode = codeOrUrl.includes("/s/") ? codeOrUrl.split("/s/").pop().trim() : codeOrUrl.trim();
	const ctx = resolveSealseekApiContext("user", deps.env);
	if (!ctx.token) throw new Error("未登录，请先完成设备登录后再导入技能");
	const client = createSealseekShareClient({
		ctx,
		fetchImpl: deps.fetchImpl
	});
	const detail = await client.getShareDetail(shareCode);
	if (!detail.claimable) throw new Error(`无法导入：${detail.unclaimableReason ?? "分享不可用"}`);
	log(`正在领取技能「${detail.title ?? shareCode}」...`);
	await client.claimShare(shareCode);
	const synced = await client.sync();
	const item = synced.skills.find((s) => s.skillId === detail.skillId) ?? synced.skills.at(-1);
	if (!item) throw new Error("领取成功但同步未返回该技能");
	const { url } = await client.getDownloadUrl(item.skillId, item.downloadToken);
	const resp = await (deps.fetchImpl ?? fetch)(url);
	if (!resp.ok) throw new Error(`下载失败 HTTP ${resp.status}`);
	const dir = await installSkillZip({
		zipBuffer: Buffer.from(await resp.arrayBuffer()),
		skillsRoot: deps.skillsRoot,
		skillName: item.name
	});
	log(`已导入技能 ${item.name}@${item.version} → ${dir}`);
}
//#endregion
export { runSkillImport };
