import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { ENV_VARS, init_paths_state, resolveHomeDir } from "./paths-state.js";
import { mkdir, readdir, rm, stat } from "fs/promises";
import { join } from "path";
import { existsSync } from "fs";
//#region src/config/profile.ts
init_logger();
init_paths_state();
const log = createLogger("Profile");
/**
* Resolve state directory for a specific profile
*/
function resolveProfileStateDir(profile) {
	const home = resolveHomeDir();
	return profile === "default" ? join(home, ".xopc") : join(home, `.xopc-${profile}`);
}
/**
* Get the name of a profile from its state directory path
*/
function getProfileNameFromDir(stateDir) {
	const home = resolveHomeDir();
	const relative = stateDir.replace(home, "").replace(/^\//, "");
	if (relative === ".xopc") return "default";
	const match = relative.match(/^\.xopc-(.+)$/);
	return match ? match[1] : "default";
}
/**
* Get the currently active profile name from environment
*/
function getCurrentProfile() {
	if (process.env[ENV_VARS.PROFILE]) return process.env[ENV_VARS.PROFILE];
	if (process.env[ENV_VARS.STATE_DIR]) return getProfileNameFromDir(process.env[ENV_VARS.STATE_DIR]);
	return "default";
}
var ProfileManager = class {
	homeDir;
	constructor() {
		this.homeDir = resolveHomeDir();
	}
	/**
	* List all available profiles
	*/
	async listProfiles() {
		const profiles = [];
		const currentProfile = getCurrentProfile();
		if (existsSync(join(this.homeDir, ".xopc"))) profiles.push(await this.getProfileInfo("default", currentProfile === "default"));
		try {
			const profileDirs = (await readdir(this.homeDir, { withFileTypes: true })).filter((entry) => entry.isDirectory() && entry.name.startsWith(".xopc-") && entry.name !== ".xopc");
			for (const dir of profileDirs) {
				const name = dir.name.replace(".xopc-", "");
				profiles.push(await this.getProfileInfo(name, currentProfile === name));
			}
		} catch (error) {
			log.warn({ error }, "Failed to list profile directories");
		}
		return profiles.sort((a, b) => {
			if (a.name === "default") return -1;
			if (b.name === "default") return 1;
			return a.name.localeCompare(b.name);
		});
	}
	/**
	* Create a new profile
	*/
	async createProfile(name) {
		if (name === "default") throw new Error("Cannot create a profile named \"default\", use \"init\" instead");
		if (!/^[a-zA-Z0-9_-]+$/.test(name)) throw new Error("Profile name must contain only letters, numbers, hyphens, and underscores");
		const stateDir = resolveProfileStateDir(name);
		if (existsSync(stateDir)) throw new Error(`Profile "${name}" already exists at ${stateDir}`);
		await mkdir(stateDir, { recursive: true });
		await mkdir(join(stateDir, "agents"), { recursive: true });
		await mkdir(join(stateDir, "credentials"), { recursive: true });
		await mkdir(join(stateDir, "extensions"), { recursive: true });
		await mkdir(join(stateDir, "skills"), { recursive: true });
		await mkdir(join(stateDir, "cron"), { recursive: true });
		await mkdir(join(stateDir, "logs"), { recursive: true });
		await mkdir(join(stateDir, "bin"), { recursive: true });
		await mkdir(join(stateDir, "tools"), { recursive: true });
		log.info({
			name,
			stateDir
		}, "Created new profile");
		return this.getProfileInfo(name, false);
	}
	/**
	* Delete a profile (with safety checks)
	*/
	async deleteProfile(name, options = {}) {
		if (name === "default") throw new Error("Cannot delete the default profile");
		const stateDir = resolveProfileStateDir(name);
		if (!existsSync(stateDir)) throw new Error(`Profile "${name}" does not exist`);
		if (getCurrentProfile() === name && !options.force) throw new Error(`Cannot delete profile "${name}" because it is currently active. Switch to another profile first or use --force.`);
		await rm(stateDir, {
			recursive: true,
			force: true
		});
		log.info({ name }, "Deleted profile");
	}
	/**
	* Get shell command to switch to a profile
	*/
	getSwitchCommand(name) {
		if (name === "default") return `unset ${ENV_VARS.PROFILE}`;
		return `export ${ENV_VARS.PROFILE}=${name}`;
	}
	/**
	* Get the profile state directory
	*/
	getProfileStateDir(name) {
		return resolveProfileStateDir(name);
	}
	async getProfileInfo(name, isActive) {
		const stateDir = resolveProfileStateDir(name);
		let agentCount = 0;
		let createdAt;
		try {
			createdAt = (await stat(stateDir)).birthtime;
			const agentsDir = join(stateDir, "agents");
			if (existsSync(agentsDir)) agentCount = (await readdir(agentsDir, { withFileTypes: true })).filter((e) => e.isDirectory()).length;
		} catch (error) {
			log.warn({
				name,
				error
			}, "Failed to get profile stats");
		}
		return {
			name,
			stateDir,
			isActive,
			agentCount,
			createdAt
		};
	}
};
let defaultManager = null;
function getProfileManager() {
	if (!defaultManager) defaultManager = new ProfileManager();
	return defaultManager;
}
async function listProfiles() {
	return getProfileManager().listProfiles();
}
async function createProfile(name) {
	return getProfileManager().createProfile(name);
}
async function deleteProfile(name, options) {
	return getProfileManager().deleteProfile(name, options);
}
function getSwitchCommand(name) {
	return getProfileManager().getSwitchCommand(name);
}
//#endregion
export { ProfileManager, createProfile, deleteProfile, getCurrentProfile, getProfileManager, getProfileNameFromDir, getSwitchCommand, listProfiles, resolveProfileStateDir };

//# sourceMappingURL=profile.js.map