import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { resolveStateDir } from "../../config/paths-state.js";
import { init_paths } from "../../config/paths.js";
import { DEFAULT_USER_FILENAME } from "../context/workspace.js";
import { createSkillConfigManager } from "../skills/config.js";
import { buildTtsSystemPromptHint } from "../../voice/tts/directives.js";
import { mergeTtsConfigFromAppConfig } from "../../voice/tts/merge-config.js";
import { selectSkillsVisibleInPrompt } from "../skills/format-skills-prompt.js";
import { buildSystemPrompt } from "./system-prompt.js";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
//#region src/agent/prompt/service-prompt-builder.ts
/**
* System Prompt Builder - Builds the complete system prompt
*
* Combines base system prompt with skill prompts and bootstrap Project Context.
*/
init_paths();
init_logger();
const log = createLogger("SystemPromptBuilder");
var SystemPromptBuilder = class {
	workspace;
	config;
	skillManager;
	constructor(config) {
		this.workspace = config.workspace;
		this.config = config.config;
		this.skillManager = config.skillManager;
	}
	build(contextFiles, options) {
		const ws = options.workspaceOverride ?? this.workspace;
		const profilePathRoot = options.profileMarkdownPathRoot ?? ws;
		if (options.systemPromptOverride?.trim()) {
			const skillPrompt = options.skillPromptText !== void 0 ? options.skillPromptText : this.skillManager.getPromptForSkillAllowlist(options.skillAllowlist, options.registeredToolNames);
			const trimmed = options.systemPromptOverride.trim();
			let fullPrompt = skillPrompt.trim() ? `${trimmed}\n\n${skillPrompt}` : trimmed;
			const ttsMerged = mergeTtsConfigFromAppConfig(this.config.messages?.tts);
			const reg = options.registeredToolNames ?? [];
			const ttsHint = buildTtsSystemPromptHint({
				enabled: ttsMerged.enabled,
				trigger: ttsMerged.trigger,
				maxTextLength: ttsMerged.maxTextLength,
				modelOverrides: ttsMerged.modelOverrides,
				textToSpeechTool: ttsMerged.enabled && reg.includes("text_to_speech")
			});
			if (ttsHint?.trim()) fullPrompt = `${fullPrompt}\n\n## Voice (TTS)\n\n${ttsHint.trim()}`;
			log.debug({
				baseLength: trimmed.length,
				skillLength: skillPrompt.length,
				totalLength: fullPrompt.length
			}, "System prompt built (override)");
			return fullPrompt;
		}
		const heartbeatEnabled = this.config.gateway?.heartbeat?.includeSystemPromptSection ?? false;
		const userTimezone = this.extractTimezone(contextFiles, profilePathRoot);
		const ttsMerged = mergeTtsConfigFromAppConfig(this.config.messages?.tts);
		const reg = options.registeredToolNames ?? [];
		const ttsSystemHint = buildTtsSystemPromptHint({
			enabled: ttsMerged.enabled,
			trigger: ttsMerged.trigger,
			maxTextLength: ttsMerged.maxTextLength,
			modelOverrides: ttsMerged.modelOverrides,
			textToSpeechTool: ttsMerged.enabled && reg.includes("text_to_speech")
		});
		const basePrompt = buildSystemPrompt(ws, {
			contextFiles,
			heartbeatEnabled,
			availableTools: this.getSkillNamesForSkillsSection({
				skillAllowlist: options.skillAllowlist,
				registeredToolNames: options.registeredToolNames
			}),
			userTimezone,
			externalMemoryInstructions: options.externalMemoryInstructions,
			ttsSystemHint
		});
		const skillPrompt = options.skillPromptText !== void 0 ? options.skillPromptText : this.skillManager.getPromptForSkillAllowlist(options.skillAllowlist, options.registeredToolNames);
		const fullPrompt = skillPrompt ? `${basePrompt}\n\n${skillPrompt}` : basePrompt;
		log.debug({
			baseLength: basePrompt.length,
			skillLength: skillPrompt?.length || 0,
			totalLength: fullPrompt.length,
			contextFileCount: contextFiles.length
		}, "System prompt built");
		return fullPrompt;
	}
	rebuild(contextFiles, options) {
		this.skillManager.reload();
		return this.build(contextFiles, options);
	}
	extractTimezone(contextFiles, profilePathRoot) {
		const userContext = contextFiles.find((file) => file.path.replace(/\\/g, "/").toLowerCase().endsWith("/user.md"));
		if (userContext?.content) {
			const match = userContext.content.match(/Timezone:\s*(.+)/i);
			if (match) return match[1].trim();
		}
		const primaryPath = join(profilePathRoot, DEFAULT_USER_FILENAME);
		if (existsSync(primaryPath)) try {
			const match = readFileSync(primaryPath, "utf-8").match(/Timezone:\s*(.+)/i);
			if (match) return match[1].trim();
		} catch {}
	}
	getSkillNamesForSkillsSection(options) {
		const skillsConfig = createSkillConfigManager(resolveStateDir()).load();
		return selectSkillsVisibleInPrompt(this.skillManager.getSkills(), skillsConfig, {
			skillAllowlist: options?.skillAllowlist,
			registeredToolNames: options?.registeredToolNames
		}).map((s) => s.name);
	}
	getSkillPrompt() {
		return this.skillManager.getPrompt();
	}
	getBasePrompt(contextFiles, options) {
		const ws = options?.workspaceOverride ?? this.workspace;
		const profilePathRoot = options?.profileMarkdownPathRoot ?? ws;
		return buildSystemPrompt(ws, {
			contextFiles,
			heartbeatEnabled: this.config.gateway?.heartbeat?.includeSystemPromptSection ?? false,
			userTimezone: this.extractTimezone(contextFiles, profilePathRoot),
			externalMemoryInstructions: options?.externalMemoryInstructions
		});
	}
};
function createSystemPromptBuilder(config) {
	return new SystemPromptBuilder(config);
}
//#endregion
export { SystemPromptBuilder, createSystemPromptBuilder };

//# sourceMappingURL=service-prompt-builder.js.map