import { r as __exportAll } from "./chunk-D_gEzPfs.js";
import { r as theme } from "./theme-C5EwWDWE.js";
import { o as loadConfig, u as writeConfigFile } from "./config-BOTdzMIB.js";
import process from "node:process";
import fs from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";

//#region src/commands/admin-unlock.ts
/**
* @module commands/admin-unlock
*
* Admin / team unlock — LOCAL ONLY, never contacts the website.
*
* Keys this machine for a fully local koi using an Anthropic API key that is
* already present in the environment (the shared key synced from Vercel env —
* e.g. `vercel env pull ~/.skykoi/.env`). There is NO password POST and NO key
* fetch from the platform; the resulting koi runs on a purely local gateway
* with the cloud mesh/peer connection cleared.
*
* Key lookup order (first non-empty wins): an explicit `--api-key`, then the
* process env, then `~/.skykoi/.env` — each checked for `ANTHROPIC_API_KEY`,
* `DEV_ADMIN_ANTHROPIC_KEY`, `SKYKOI_ADMIN_ANTHROPIC_KEY`. The key is persisted
* into `~/.skykoi/skykoi.json` (home dir, untouched by npm), so the unlock
* survives reinstalls and updates.
*/
var admin_unlock_exports = /* @__PURE__ */ __exportAll({
	adminUnlock: () => adminUnlock,
	adminUnlockCommand: () => adminUnlockCommand
});
/** Env var names searched for the Anthropic key, in priority order. */
const KEY_ENV_VARS = [
	"ANTHROPIC_API_KEY",
	"DEV_ADMIN_ANTHROPIC_KEY",
	"SKYKOI_ADMIN_ANTHROPIC_KEY"
];
const FABLE_MODEL_REF = "anthropic/claude-fable-5";
/**
* Parse simple `KEY=VALUE` lines from `~/.skykoi/.env` (where the user can
* drop the Vercel-pulled env). Best-effort: returns {} when the file is absent.
* Reading from a file — not just `process.env` — lets a koi launched by the
* macOS app (which doesn't inherit the shell env) still find the key.
*/
function readSkykoiEnvFile() {
	const out = {};
	try {
		const raw = fs.readFileSync(join(homedir(), ".skykoi", ".env"), "utf8");
		for (const line of raw.split(/\r?\n/)) {
			const match = /^\s*(?:export\s+)?([A-Za-z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line);
			if (!match) continue;
			let value = match[2];
			if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
			out[match[1]] = value;
		}
	} catch {}
	return out;
}
/** Resolve the Anthropic key from an explicit override, the process env, then `~/.skykoi/.env`. */
function resolveAnthropicKey(explicit) {
	const fromExplicit = explicit?.trim();
	if (fromExplicit) return fromExplicit;
	for (const name of KEY_ENV_VARS) {
		const value = process.env[name]?.trim();
		if (value) return value;
	}
	const fileEnv = readSkykoiEnvFile();
	for (const name of KEY_ENV_VARS) {
		const value = fileEnv[name]?.trim();
		if (value) return value;
	}
	return null;
}
/**
* Write the local-only Anthropic config: a direct api-key provider on Fable 5,
* a local gateway, and the cloud mesh/peer connection removed — so nothing
* dials www.skykoi.com or the cloud gateway. Preserves any other config.
*/
async function applyLocalConfig(apiKey) {
	const config = loadConfig();
	const models = config.models ??= {};
	const providers = models.providers ??= {};
	providers.anthropic = {
		baseUrl: "https://api.anthropic.com",
		api: "anthropic-messages",
		auth: "api-key",
		apiKey,
		models: [{
			id: "claude-fable-5",
			name: "Claude Fable 5",
			reasoning: true,
			input: ["text", "image"],
			cost: {
				input: 10,
				output: 50,
				cacheRead: 1,
				cacheWrite: 12.5
			},
			contextWindow: 1e6,
			maxTokens: 64e3
		}]
	};
	const kois = config.kois ??= {};
	const defaults = kois.defaults ??= {};
	defaults.model = { primary: FABLE_MODEL_REF };
	const gateway = config.gateway ??= {};
	gateway.mode = "local";
	delete gateway.remote;
	gateway.mesh = {
		...gateway.mesh ?? {},
		enabled: false
	};
	await writeConfigFile(config);
}
/**
* Run the local admin unlock end-to-end: resolve the key from the environment,
* write the local-only config, and make sure a local gateway is running. Never
* touches the network except the local gateway it serves the koi from.
*/
async function adminUnlock(opts = {}) {
	const apiKey = resolveAnthropicKey(opts.apiKey);
	if (!apiKey) return {
		ok: false,
		error: "No Anthropic API key found in the environment. Load it from Vercel — e.g. `vercel env pull ~/.skykoi/.env` (or `export ANTHROPIC_API_KEY=…`) — then run `koi admin` again. Admin is local-only and never contacts the website."
	};
	try {
		await applyLocalConfig(apiKey);
	} catch (err) {
		return {
			ok: false,
			error: err?.message ?? "Failed to write config"
		};
	}
	const { ensureLocalGatewayRunning } = await import("./ensure-local-gateway-CwgaMY79.js").then((n) => n.n);
	const gw = await ensureLocalGatewayRunning();
	if (!gw.ok) return {
		ok: false,
		error: `Keys configured, but ${gw.error}. Try \`koi gateway run\`.`
	};
	return { ok: true };
}
/**
* Whether this process can read the Messages DB, i.e. macOS Full Disk Access
* is granted. The koi needs it to map the user's real contact graph from
* iMessage + WhatsApp during onboarding; without it those sources are dark.
*/
function fullDiskAccessGranted() {
	try {
		const fd = fs.openSync(join(homedir(), "Library", "Messages", "chat.db"), "r");
		fs.closeSync(fd);
		return true;
	} catch {
		return false;
	}
}
/**
* CLI entry for `koi admin` — runs the local unlock and prints a friendly
* result. Resolves to true on success so callers can route onward.
*/
async function adminUnlockCommand(opts = {}) {
	const result = await adminUnlock(opts);
	if (result.ok) {
		console.log(`\n${theme.success("✓ Admin access unlocked (local).")} Claude Fable 5 is configured on this machine from your environment. Run ${theme.command("koi")} to start. ` + theme.muted("(Local-only: no website, no cloud gateway. Persists across updates.)"));
		if (!fullDiskAccessGranted()) console.log(`\n${theme.muted("One step for full power: grant Full Disk Access so the koi can learn your")} ${theme.muted("real network from Messages + WhatsApp during onboarding.")}\n${theme.muted("System Settings > Privacy & Security > Full Disk Access > enable Terminal, then relaunch.")}`);
		return true;
	}
	console.error(`\n${theme.error("✗ " + result.error)}`);
	return false;
}

//#endregion
export { admin_unlock_exports as n, adminUnlockCommand as t };