import { init_write_file_atomic, writeTextAtomicSync } from "../../infra/write-file-atomic.js";
import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { homedir } from "os";
//#region src/auth/profiles/store.ts
/**
* Auth Profile Store
* 
* Persistent storage for auth profiles.
* Handles loading and saving auth credentials.
*/
init_write_file_atomic();
const AUTH_STORE_VERSION = 1;
const AUTH_STORE_FILENAME = "auth-profiles.json";
/** Get the auth profiles file path */
function resolveAuthStorePath(dataDir) {
	const dir = dataDir ?? path.join(homedir(), ".xopc");
	return path.join(dir, AUTH_STORE_FILENAME);
}
/** Ensure auth store file exists */
function ensureAuthStoreFile(authPath) {
	const dir = path.dirname(authPath);
	if (!existsSync(dir)) mkdirSync(dir, {
		recursive: true,
		mode: 448
	});
	if (!existsSync(authPath)) {
		writeTextAtomicSync(authPath, JSON.stringify({
			version: AUTH_STORE_VERSION,
			profiles: {}
		}, null, 2));
		chmodSync(authPath, 384);
	}
}
function loadJsonFile(filePath) {
	if (!existsSync(filePath)) return null;
	try {
		const content = readFileSync(filePath, "utf-8");
		return JSON.parse(content);
	} catch {
		return null;
	}
}
function saveJsonFile(filePath, data) {
	const dir = path.dirname(filePath);
	if (!existsSync(dir)) mkdirSync(dir, {
		recursive: true,
		mode: 448
	});
	writeTextAtomicSync(filePath, JSON.stringify(data, null, 2));
	chmodSync(filePath, 384);
}
function coerceAuthStore(raw) {
	if (!raw || typeof raw !== "object") return null;
	const record = raw;
	if (!record.profiles || typeof record.profiles !== "object") return null;
	const profiles = record.profiles;
	const normalized = {};
	for (const [key, value] of Object.entries(profiles)) {
		if (!value || typeof value !== "object") continue;
		const typed = value;
		if (typed.type !== "api_key" && typed.type !== "oauth" && typed.type !== "token") continue;
		if (!typed.provider) continue;
		normalized[key] = typed;
	}
	const order = record.order && typeof record.order === "object" ? Object.entries(record.order).reduce((acc, [provider, value]) => {
		if (!Array.isArray(value)) return acc;
		const list = value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter(Boolean);
		if (list.length === 0) return acc;
		acc[provider] = list;
		return acc;
	}, {}) : void 0;
	return {
		version: Number(record.version ?? AUTH_STORE_VERSION),
		profiles: normalized,
		order,
		lastGood: record.lastGood && typeof record.lastGood === "object" ? record.lastGood : void 0,
		usageStats: record.usageStats && typeof record.usageStats === "object" ? record.usageStats : void 0
	};
}
/** Load auth profile store from disk */
function loadAuthProfileStore(dataDir) {
	const asStore = coerceAuthStore(loadJsonFile(resolveAuthStorePath(dataDir)));
	if (asStore) return asStore;
	return {
		version: AUTH_STORE_VERSION,
		profiles: {}
	};
}
/** Ensure auth profile store exists */
function ensureAuthProfileStore(dataDir) {
	ensureAuthStoreFile(resolveAuthStorePath(dataDir));
	return loadAuthProfileStore(dataDir);
}
/** Save auth profile store to disk */
function saveAuthProfileStore(store, dataDir) {
	saveJsonFile(resolveAuthStorePath(dataDir), {
		version: AUTH_STORE_VERSION,
		profiles: store.profiles,
		order: store.order ?? void 0,
		lastGood: store.lastGood ?? void 0,
		usageStats: store.usageStats ?? void 0
	});
}
//#endregion
export { ensureAuthProfileStore, ensureAuthStoreFile, loadAuthProfileStore, resolveAuthStorePath, saveAuthProfileStore };

//# sourceMappingURL=store.js.map