import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, rmSync } from "fs";
import { join } from "path";
import { DATA_DIR, WORKSPACES_DIR } from "../utils/paths.js";
const AGENTS_DIR = join(DATA_DIR, "agents");
function ensureAgentsDir() {
    if (!existsSync(AGENTS_DIR)) {
        mkdirSync(AGENTS_DIR, { recursive: true });
    }
}
// Ensure directory exists on import
ensureAgentsDir();
export function getAgentDataDir(alias) {
    return join(AGENTS_DIR, alias);
}
function agentDir(alias) {
    return join(AGENTS_DIR, alias);
}
function configPath(alias) {
    return join(agentDir(alias), "agent.json");
}
/** Validate alias: lowercase alphanumeric, hyphens, underscores only */
export function isValidAlias(alias) {
    return /^[a-z0-9][a-z0-9_-]*$/.test(alias) && alias.length >= 2 && alias.length <= 64;
}
export function agentExists(alias) {
    return existsSync(configPath(alias));
}
export function createAgent(config) {
    const dir = agentDir(config.alias);
    mkdirSync(dir, { recursive: true });
    writeFileSync(configPath(config.alias), JSON.stringify(config, null, 2));
}
export function getAgent(alias) {
    const path = configPath(alias);
    if (!existsSync(path))
        return undefined;
    const data = readFileSync(path, "utf8");
    return JSON.parse(data);
}
export function listAgents() {
    ensureAgentsDir();
    const entries = readdirSync(AGENTS_DIR, { withFileTypes: true });
    const agents = [];
    for (const entry of entries) {
        if (!entry.isDirectory())
            continue;
        const config = getAgent(entry.name);
        if (config)
            agents.push(config);
    }
    // Sort by creation time, newest first
    agents.sort((a, b) => b.createdAt - a.createdAt);
    return agents;
}
export function deleteAgent(alias) {
    const dir = agentDir(alias);
    if (!existsSync(dir))
        return false;
    rmSync(dir, { recursive: true, force: true });
    return true;
}
/** Resolve the workspace directory path for an agent (e.g., ~/.callboard/agent-workspaces/{alias}) */
export function getAgentWorkspacePath(alias) {
    return join(WORKSPACES_DIR, alias);
}
/** Ensure the workspace directory exists and return its path */
export function ensureAgentWorkspaceDir(alias) {
    const workspacePath = getAgentWorkspacePath(alias);
    if (!existsSync(workspacePath)) {
        mkdirSync(workspacePath, { recursive: true });
    }
    return workspacePath;
}
