import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { getManager } from "./utils.js";
//#region src/cli/commands/session/actions.ts
init_logger();
const log = createLogger("SessionCommand");
function formatMessageContentForCli(content) {
	if (typeof content === "string") return content;
	if (Array.isArray(content)) return content.map((block) => {
		if (!block || typeof block !== "object") return "";
		const b = block;
		if (b.type === "text" && typeof b.text === "string") return b.text;
		if (b.type === "toolCall" || b.type === "tool_use") return `[${String(b.name ?? "tool")}]`;
		return "";
	}).join(" ");
	return "";
}
async function listSessions(options) {
	const manager = await getManager();
	const query = {
		channel: options.channel,
		status: options.status,
		tags: options.tag.length > 0 ? options.tag : void 0,
		search: options.query,
		sortBy: options.sort,
		sortOrder: options.order,
		limit: parseInt(options.limit),
		offset: parseInt(options.offset)
	};
	const result = await manager.listSessions(query);
	console.log(`\n📋 Sessions (${result.items.length} of ${result.total}):\n`);
	if (result.items.length === 0) {
		console.log("No sessions found.");
		return;
	}
	console.log("Key".padEnd(30) + "Name".padEnd(20) + "Status".padEnd(10) + "Messages".padEnd(10) + "Updated");
	console.log("─".repeat(90));
	for (const session of result.items) {
		const name = (session.name || "-").slice(0, 18).padEnd(20);
		const status = session.status.padEnd(10);
		const messages = String(session.messageCount).padEnd(10);
		const updated = new Date(session.updatedAt).toLocaleDateString();
		console.log(`${session.key.slice(0, 28).padEnd(30)}${name}${status}${messages}${updated}`);
	}
	if (result.hasMore) console.log(`\n... and ${result.total - result.offset - result.limit} more`);
	console.log();
}
async function getSessionInfo(key) {
	const session = await (await getManager()).getSession(key);
	if (!session) {
		console.error(`❌ Session not found: ${key}`);
		process.exit(1);
	}
	console.log(`\n📁 Session: ${session.key}\n`);
	console.log(`  Name:        ${session.name || "-"}`);
	console.log(`  Status:      ${session.status}`);
	console.log(`  Tags:        ${session.tags.join(", ") || "-"}`);
	console.log(`  Channel:     ${session.sourceChannel}`);
	console.log(`  Chat ID:     ${session.sourceChatId}`);
	console.log(`  Messages:    ${session.messageCount}`);
	console.log(`  Est. Tokens: ${session.estimatedTokens.toLocaleString()}`);
	console.log(`  Compacted:   ${session.compactedCount} times`);
	console.log(`  Created:     ${new Date(session.createdAt).toLocaleString()}`);
	console.log(`  Updated:     ${new Date(session.updatedAt).toLocaleString()}`);
	console.log(`  Last Access: ${new Date(session.lastAccessedAt).toLocaleString()}`);
	if (session.messages.length > 0) {
		console.log(`\n  Recent Messages:`);
		const recent = session.messages.slice(-5);
		for (const msg of recent) {
			const role = msg.role.padEnd(10);
			const text = formatMessageContentForCli(msg.content);
			const preview = text.slice(0, 60).replace(/\n/g, " ");
			console.log(`    ${role}: ${preview}${text.length > 60 ? "..." : ""}`);
		}
	}
	console.log();
}
async function deleteSession(key, options) {
	if (!options.force) {
		const { confirm } = await import("@inquirer/prompts");
		if (!await confirm({
			message: `Are you sure you want to delete session "${key}"?`,
			default: false
		})) {
			console.log("Cancelled.");
			return;
		}
	}
	await (await getManager()).deleteSession(key);
	console.log(`✅ Session deleted: ${key}`);
}
async function deleteMany(options) {
	const manager = await getManager();
	const query = {
		status: options.status,
		channel: options.channel,
		limit: 1e3
	};
	const result = await manager.listSessions(query);
	if (result.items.length === 0) {
		console.log("No sessions match the criteria.");
		return;
	}
	const keys = result.items.map((s) => s.key);
	console.log(`Found ${keys.length} sessions to delete.`);
	if (!options.force) {
		const { confirm } = await import("@inquirer/prompts");
		if (!await confirm({
			message: `Delete ${keys.length} sessions?`,
			default: false
		})) {
			console.log("Cancelled.");
			return;
		}
	}
	const deleteResult = await manager.deleteSessions(keys);
	console.log(`✅ Deleted ${deleteResult.success.length} sessions`);
	if (deleteResult.failed.length > 0) console.log(`❌ Failed to delete ${deleteResult.failed.length} sessions`);
}
async function renameSession(key, name) {
	await (await getManager()).renameSession(key, name);
	console.log(`✅ Session renamed to: ${name}`);
}
async function tagSession(key, tags) {
	await (await getManager()).tagSession(key, tags);
	console.log(`✅ Tags added: ${tags.join(", ")}`);
}
async function untagSession(key, tags) {
	await (await getManager()).untagSession(key, tags);
	console.log(`✅ Tags removed: ${tags.join(", ")}`);
}
async function archiveSession(key) {
	await (await getManager()).archiveSession(key);
	console.log(`✅ Session archived: ${key}`);
}
async function unarchiveSession(key) {
	await (await getManager()).unarchiveSession(key);
	console.log(`✅ Session unarchived: ${key}`);
}
async function pinSession(key) {
	await (await getManager()).pinSession(key);
	console.log(`✅ Session pinned: ${key}`);
}
async function unpinSession(key) {
	await (await getManager()).unpinSession(key);
	console.log(`✅ Session unpinned: ${key}`);
}
async function searchSessions(query) {
	const sessions = await (await getManager()).searchSessions(query);
	console.log(`\n🔍 Search results for "${query}" (${sessions.length} found):\n`);
	if (sessions.length === 0) {
		console.log("No sessions found.");
		return;
	}
	for (const session of sessions) {
		console.log(`  ${session.key}`);
		if (session.name) console.log(`    Name: ${session.name}`);
		console.log(`    Status: ${session.status} | Messages: ${session.messageCount}`);
		console.log(`    Tags: ${session.tags.join(", ") || "-"}`);
		console.log();
	}
}
async function grepSession(key, keyword) {
	const messages = await (await getManager()).searchInSession(key, keyword);
	console.log(`\n🔍 Found ${messages.length} messages containing "${keyword}":\n`);
	for (const msg of messages) {
		const role = msg.role.padEnd(10);
		const text = formatMessageContentForCli(msg.content);
		const highlighted = text.replace(new RegExp(keyword, "gi"), (match) => `\x1b[33m${match}\x1b[0m`);
		console.log(`  ${role}: ${highlighted.slice(0, 200)}${text.length > 200 ? "..." : ""}\n`);
	}
}
async function exportSession(key, options) {
	const manager = await getManager();
	const format = options.format;
	const content = await manager.exportSession(key, format);
	if (options.output) {
		const { writeFile } = await import("fs/promises");
		await writeFile(options.output, content);
		console.log(`✅ Exported to: ${options.output}`);
	} else console.log(content);
}
async function showStats() {
	const stats = await (await getManager()).getStats();
	console.log("\n📊 Session Statistics\n");
	console.log(`  Total Sessions:     ${stats.totalSessions}`);
	console.log(`  Active:             ${stats.activeSessions}`);
	console.log(`  Archived:           ${stats.archivedSessions}`);
	console.log(`  Pinned:             ${stats.pinnedSessions}`);
	console.log(`  Total Messages:     ${stats.totalMessages.toLocaleString()}`);
	console.log(`  Total Tokens:       ${stats.totalTokens.toLocaleString()}`);
	if (stats.oldestSession) console.log(`  Oldest Session:     ${new Date(stats.oldestSession).toLocaleDateString()}`);
	if (stats.newestSession) console.log(`  Newest Session:     ${new Date(stats.newestSession).toLocaleDateString()}`);
	if (Object.keys(stats.byChannel).length > 0) {
		console.log("\n  By Channel:");
		for (const [channel, count] of Object.entries(stats.byChannel)) console.log(`    ${channel}: ${count}`);
	}
	console.log();
}
async function cleanup(options) {
	const days = parseInt(options.days);
	if (!options.force) {
		const { confirm } = await import("@inquirer/prompts");
		if (!await confirm({
			message: `Archive all sessions inactive for more than ${days} days?`,
			default: false
		})) {
			console.log("Cancelled.");
			return;
		}
	}
	const count = await (await getManager()).archiveOldSessions(days);
	console.log(`✅ Archived ${count} sessions`);
}
function handleError(error, message) {
	log.error({ err: error }, message);
	process.exit(1);
}
//#endregion
export { archiveSession, cleanup, deleteMany, deleteSession, exportSession, getSessionInfo, grepSession, handleError, listSessions, pinSession, renameSession, searchSessions, showStats, tagSession, unarchiveSession, unpinSession, untagSession };

//# sourceMappingURL=actions.js.map