import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync } from 'node:fs';
import * as store from '../storage/chat-store.js';
import { listProviders } from '../storage/llm-store.js';
// --- Agent CRUD ---
export function listAgents() {
    return store.listAgents().map(hydrateAgentProvider);
}
export function createAgent(data) {
    const id = randomUUID();
    const now = new Date().toISOString();
    const agent = {
        ...normalizeAgentData(data),
        id,
        workingDir: store.chatWorkspaceDir(id),
        createdAt: now,
        updatedAt: now,
    };
    store.saveAgent(agent, data.skills);
    return hydrateAgentProvider(agent);
}
export function updateAgent(id, data) {
    const existing = store.findAgent(id);
    if (!existing)
        return null;
    const updated = {
        ...existing,
        ...normalizeAgentData({ ...existing, ...data }),
        id,
        createdAt: existing.createdAt,
        workingDir: store.chatWorkspaceDir(id),
        updatedAt: new Date().toISOString(),
    };
    store.saveAgent(updated, data.skills);
    return hydrateAgentProvider(updated);
}
export function deleteAgent(id) {
    if (!store.findAgent(id))
        return false;
    store.deleteAgent(id);
    return true;
}
export function findAgent(id) {
    const agent = store.findAgent(id);
    return agent ? hydrateAgentProvider(agent) : undefined;
}
// --- Message CRUD ---
export function listMessages(agentId, limit, before) {
    return store.listMessages(agentId, limit, before);
}
export function saveMessage(msg) {
    const message = {
        ...msg,
        id: randomUUID(),
        timestamp: new Date().toISOString(),
    };
    store.saveMessage(message);
    return message;
}
export function clearMessages(agentId) {
    store.deleteMessagesByAgent(agentId);
}
export function getRecentMessages(agentId, limit) {
    return store.getRecentMessages(agentId, limit);
}
export function getAgentWorkingDir(agentId) {
    const agent = store.findAgent(agentId);
    if (!agent)
        return null;
    return agent.workingDir || store.chatWorkspaceDir(agentId);
}
export function getAgentConfigDir(agentId) {
    return store.findAgent(agentId) ? store.agentDir(agentId) : null;
}
export function resolveProviderIdFromChatAgentInput(data) {
    return stringValue(data.providerId) || resolveProviderConfig(data)?.id || '';
}
export function getAgentWorkspace(agentId) {
    const workingDir = getAgentWorkingDir(agentId);
    if (!workingDir)
        return null;
    if (!existsSync(workingDir)) {
        const defaultWorkingDir = store.chatWorkspaceDir(agentId);
        if (workingDir !== defaultWorkingDir)
            return null;
        mkdirSync(workingDir, { recursive: true });
    }
    const now = new Date().toISOString();
    return {
        id: `chat:${agentId}`,
        name: 'Chat Agent',
        boundDirs: [workingDir],
        agentspaceDir: workingDir,
        createdAt: now,
        updatedAt: now,
        activeChannels: [],
        activeIssues: [],
    };
}
// --- Workspace CRUD ---
export function listWorkspaces() {
    return store.listWorkspaces();
}
export function createWorkspace(data) {
    return store.createWorkspace(data);
}
export function updateWorkspace(id, data) {
    return store.updateWorkspace(id, data);
}
export function deleteWorkspace(id) {
    return store.deleteWorkspace(id);
}
// --- Session CRUD ---
export function listSessions(workspaceId) {
    return store.listSessions(workspaceId);
}
export function createSession(workspaceId, agentId) {
    return store.createSession(workspaceId, agentId);
}
export function updateSession(workspaceId, sessionId, data) {
    return store.updateSession(workspaceId, sessionId, data);
}
export function deleteSession(workspaceId, sessionId) {
    return store.deleteSession(workspaceId, sessionId);
}
export function findSession(workspaceId, sessionId) {
    return store.findSession(workspaceId, sessionId);
}
// --- Session Messages ---
export function listSessionMessages(workspaceId, sessionId) {
    return store.listSessionMessages(workspaceId, sessionId);
}
export function saveSessionMessage(workspaceId, sessionId, msg) {
    const message = {
        ...msg,
        id: randomUUID(),
        timestamp: new Date().toISOString(),
    };
    store.saveSessionMessage(workspaceId, sessionId, message);
    return message;
}
export function clearSessionMessages(workspaceId, sessionId) {
    store.clearSessionMessages(workspaceId, sessionId);
}
export function getRecentSessionMessages(workspaceId, sessionId, limit) {
    return store.getRecentSessionMessages(workspaceId, sessionId, limit);
}
// --- Migration ---
export { migrateToWorkspaces } from '../storage/chat-store.js';
function normalizeAgentData(data) {
    const provider = stringValue(data.provider) || stringValue(data.modelProvider) || 'openai-chat-completions';
    const model = stringValue(data.model) || stringValue(data.modelId) || '';
    const providerConfig = resolveProviderConfig(data);
    const baseURL = providerConfig?.apiBase || stringValue(data.baseURL) || stringValue(data.apiBase) || undefined;
    const avatar = stringValue(data.avatar) || stringValue(data.avatarUrl) || undefined;
    const skills = normalizeSkillNames(data.skills);
    return {
        name: stringValue(data.name) || 'New Chat Agent',
        role: 'agent',
        runtimeKind: 'langchain',
        avatar,
        avatarUrl: avatar,
        icon: stringValue(data.icon) || undefined,
        description: stringValue(data.description) || undefined,
        systemPrompt: stringValue(data.systemPrompt) || undefined,
        provider,
        modelProvider: provider,
        providerId: stringValue(data.providerId) || providerConfig?.id || undefined,
        model,
        modelId: model,
        apiKey: providerConfig?.apiKey || stringValue(data.apiKey) || undefined,
        baseURL,
        apiBase: baseURL,
        workingDir: stringValue(data.workingDir),
        mcps: isRecord(data.mcps) ? data.mcps : {},
        skills,
        tools: Array.isArray(data.tools) ? data.tools : [],
        outputStyle: stringValue(data.outputStyle) || undefined,
        temperature: typeof data.temperature === 'number' ? data.temperature : 0.3,
        maxTokens: typeof data.maxTokens === 'number' ? data.maxTokens : 4096,
        enabled: data.enabled !== false,
    };
}
function resolveProviderConfig(data) {
    const providers = listProviders();
    const providerId = stringValue(data.providerId);
    if (providerId) {
        const byId = providers.find((provider) => provider.id === providerId);
        if (byId)
            return byId;
    }
    const apiBase = stringValue(data.apiBase) || stringValue(data.baseURL);
    const apiKey = stringValue(data.apiKey);
    if (!apiBase && !apiKey)
        return undefined;
    return providers.find((provider) => (!apiBase || provider.apiBase === apiBase)
        && (!apiKey || provider.apiKey === apiKey));
}
function hydrateAgentProvider(agent) {
    const provider = resolveProviderConfig(agent);
    if (!provider) {
        return {
            ...agent,
            provider: agent.provider || agent.modelProvider || 'openai-chat-completions',
            baseURL: agent.baseURL || agent.apiBase,
            apiBase: agent.apiBase || agent.baseURL,
        };
    }
    return {
        ...agent,
        providerId: provider.id,
        provider: agent.provider || agent.modelProvider || 'openai-chat-completions',
        apiKey: provider.apiKey,
        baseURL: provider.apiBase,
        apiBase: provider.apiBase,
    };
}
function stringValue(value) {
    return typeof value === 'string' ? value.trim() : '';
}
function isRecord(value) {
    return !!value && typeof value === 'object' && !Array.isArray(value);
}
function normalizeSkillNames(skills) {
    if (!Array.isArray(skills))
        return [];
    return skills
        .map(skill => typeof skill === 'string' ? skill : isRecord(skill) ? stringValue(skill.name) : '')
        .filter(Boolean);
}
//# sourceMappingURL=chat.js.map