import { c as resolveDefaultAgentId, o as resolveAgentWorkspaceDir } from "./agent-scope-config-DkpPMLgw.js";
import "./agent-scope-nQ3Sziuh.js";
import { i as getRuntimeConfig } from "./io-CYCDSQdU.js";
import { a as sendMethodNotAllowed, i as sendJson, t as readJsonBodyOrError } from "./http-common-D7WyQCLw.js";
import { t as authorizeControlUiReadRequest } from "./control-ui-DwBudshf.js";
import { a as writeCredentialsDefaultAccount, t as CREDENTIALS_DIR } from "./credentials-proxy-http-CH6Vwhpk.js";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/gateway/platform-accounts-http.ts
const PLATFORM_ACCOUNTS_FILENAME = ".platform-accounts.json";
function isPlatformAccountsPath(pathname) {
	return pathname === "/workspace/platform-accounts";
}
async function readPlatformAccounts(workspaceDir) {
	const filePath = path.join(workspaceDir, PLATFORM_ACCOUNTS_FILENAME);
	try {
		const text = await fs.readFile(filePath, "utf-8");
		return JSON.parse(text);
	} catch {
		return { selections: {} };
	}
}
async function writePlatformAccount(workspaceDir, platform, subPlatform, accountId) {
	const filePath = path.join(workspaceDir, PLATFORM_ACCOUNTS_FILENAME);
	const data = await readPlatformAccounts(workspaceDir);
	if (!data.selections || typeof data.selections !== "object") data.selections = {};
	data.selections[`${platform}:${subPlatform}`] = accountId;
	await fs.mkdir(workspaceDir, { recursive: true });
	await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
}
/**
* Persist a switched-account selection to BOTH stores:
* - workspace `.platform-accounts.json` (per-agent selection)
* - credentials `{platform}/{sub_platform}/default` (the global default
*   pointer consumed by `/credentials/status` and any agent code reading the
*   default credential)
*
* The workspace POST handler must call this — writing only the workspace
* file leaves the credentials `default` pointing at the previously-used
* account, so status checks and downstream consumers keep validating the
* stale account.
*/
async function saveAccountSelection(workspaceDir, credentialsDir, platform, subPlatform, accountId) {
	await writePlatformAccount(workspaceDir, platform, subPlatform, accountId);
	await writeCredentialsDefaultAccount(credentialsDir, platform, accountId);
}
async function handlePlatformAccountsHttpRequest(req, res, opts) {
	const cfg = getRuntimeConfig();
	if (!isPlatformAccountsPath(new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`).pathname)) return false;
	if (req.method !== "GET" && req.method !== "POST") {
		sendMethodNotAllowed(res, "GET, POST");
		return true;
	}
	if (!await authorizeControlUiReadRequest(req, res, {
		auth: opts.auth,
		trustedProxies: opts.trustedProxies ?? cfg.gateway?.trustedProxies,
		allowRealIpFallback: opts.allowRealIpFallback ?? cfg.gateway?.allowRealIpFallback,
		rateLimiter: opts.rateLimiter
	})) return true;
	const workspaceDir = resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
	if (req.method === "GET") {
		sendJson(res, 200, await readPlatformAccounts(workspaceDir));
		return true;
	}
	const bodyUnknown = await readJsonBodyOrError(req, res, 65536);
	if (bodyUnknown === void 0) return true;
	const { platform, sub_platform, account_id } = bodyUnknown;
	if (!platform || !sub_platform || !account_id) {
		sendJson(res, 400, {
			ok: false,
			error: "platform, sub_platform, account_id are required"
		});
		return true;
	}
	await saveAccountSelection(workspaceDir, CREDENTIALS_DIR, platform, sub_platform, account_id);
	sendJson(res, 200, { ok: true });
	return true;
}
//#endregion
export { handlePlatformAccountsHttpRequest, isPlatformAccountsPath, readPlatformAccounts, saveAccountSelection, writePlatformAccount };
