import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { readdir, realpath, stat } from "node:fs/promises";
import * as path$1 from "node:path";
import * as os$1 from "node:os";
//#region src/gateway/hono/routes/host-fs.ts
init_logger();
const log = createLogger("HostFs");
function jsonError(status, message) {
	return Response.json({
		ok: false,
		error: { message }
	}, { status });
}
function skipDotName(name) {
	return name.startsWith(".");
}
/** Windows: true if `p` is a drive root like `C:\`. */
function isWindowsDriveRoot(p) {
	return /^[A-Za-z]:\\?$/.test(path$1.normalize(p).replace(/\\$/, "\\"));
}
function parentDirectory(absNormalized) {
	if (process.platform === "win32") {
		const n = path$1.normalize(absNormalized);
		if (isWindowsDriveRoot(n)) return null;
		const d = path$1.dirname(n);
		if (d === n) return null;
		return d;
	}
	const n = path$1.normalize(absNormalized);
	if (n === "/" || n === path$1.parse(n).root) return null;
	const d = path$1.dirname(n);
	if (d === n) return null;
	return d;
}
async function listWindowsDrives() {
	const entries = [];
	for (let i = 0; i < 26; i++) {
		const root = `${String.fromCharCode(65 + i)}:\\`;
		try {
			await stat(root);
			entries.push({
				name: root,
				absolutePath: root,
				isDirectory: true
			});
		} catch {}
	}
	entries.sort((a, b) => a.name.localeCompare(b.name));
	return entries;
}
function registerHostFsRoutes(authenticated, _deps) {
	authenticated.get("/api/host/fs/meta", (c) => {
		return c.json({
			ok: true,
			payload: {
				hostname: os$1.hostname(),
				platform: process.platform,
				pathSeparator: path$1.sep
			}
		});
	});
	/**
	* GET /api/host/fs/list?path=
	* - Omit or empty `path`: root — `/` on POSIX; drive letters on Windows.
	* - Otherwise: absolute path on the gateway host (URL-encoded).
	*/
	authenticated.get("/api/host/fs/list", async (c) => {
		const raw = c.req.query("path");
		const trimmed = typeof raw === "string" ? raw.trim() : "";
		if (!trimmed) {
			if (process.platform === "win32") try {
				const entries = await listWindowsDrives();
				return c.json({
					ok: true,
					payload: {
						currentPath: "",
						parentPath: null,
						entries
					}
				});
			} catch (err) {
				log.warn({ err }, "host fs list drives failed");
				return jsonError(500, "Failed to list drives");
			}
			try {
				const root = await realpath("/");
				const dirents = await readdir(root, { withFileTypes: true });
				const entries = [];
				for (const e of dirents) {
					if (skipDotName(e.name)) continue;
					const fullPath = path$1.join(root, e.name);
					if (e.isDirectory()) entries.push({
						name: e.name,
						absolutePath: fullPath,
						isDirectory: true
					});
					else entries.push({
						name: e.name,
						absolutePath: fullPath,
						isDirectory: false
					});
				}
				entries.sort((a, b) => {
					if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
					return a.name.localeCompare(b.name);
				});
				return c.json({
					ok: true,
					payload: {
						currentPath: root,
						parentPath: null,
						entries
					}
				});
			} catch (err) {
				log.warn({ err }, "host fs list root failed");
				return jsonError(500, (err instanceof Error ? err.message : String(err)) || "Failed to read root");
			}
		}
		let resolved;
		try {
			resolved = await realpath(path$1.normalize(trimmed));
		} catch (err) {
			log.warn({
				err,
				path: trimmed
			}, "host fs realpath failed");
			return jsonError(404, "Path not found");
		}
		let st;
		try {
			st = await stat(resolved);
		} catch (err) {
			log.warn({
				err,
				path: resolved
			}, "host fs stat failed");
			return jsonError(404, "Path not found");
		}
		if (!st.isDirectory()) return jsonError(400, "Not a directory");
		const parentPath = parentDirectory(resolved);
		try {
			const dirents = await readdir(resolved, { withFileTypes: true });
			const entries = [];
			for (const e of dirents) {
				if (skipDotName(e.name)) continue;
				const fullPath = path$1.join(resolved, e.name);
				entries.push({
					name: e.name,
					absolutePath: fullPath,
					isDirectory: e.isDirectory()
				});
			}
			entries.sort((a, b) => {
				if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
				return a.name.localeCompare(b.name);
			});
			return c.json({
				ok: true,
				payload: {
					currentPath: resolved,
					parentPath,
					entries
				}
			});
		} catch (err) {
			log.warn({
				err,
				path: resolved
			}, "host fs readdir failed");
			const msg = err instanceof Error ? err.message : String(err);
			if (err?.code === "EACCES") return jsonError(403, "Permission denied");
			return jsonError(500, msg || "Failed to read directory");
		}
	});
}
//#endregion
export { registerHostFsRoutes };

//# sourceMappingURL=host-fs.js.map