import { a as isOAuthToken, b as paths, f as secureFetch } from "./index.mjs";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir, platform } from "node:os";
import { dirname, join } from "node:path";

//#region src/auth/model-presets.ts
const PRESETS = {
	anthropic: {
		extraction: {
			provider: "google",
			model: "gemini-2.5-flash"
		},
		reasoning: {
			provider: "anthropic",
			model: "claude-sonnet-4-5"
		},
		deep: {
			provider: "anthropic",
			model: "claude-opus-4-6"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	},
	openai: {
		extraction: {
			provider: "openai",
			model: "gpt-4o-mini"
		},
		reasoning: {
			provider: "openai",
			model: "gpt-4o"
		},
		deep: {
			provider: "openai",
			model: "gpt-4o"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	},
	google: {
		extraction: {
			provider: "google",
			model: "gemini-2.5-flash"
		},
		reasoning: {
			provider: "google",
			model: "gemini-2.5-pro"
		},
		deep: {
			provider: "google",
			model: "gemini-2.5-pro"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	},
	ollama: {
		extraction: {
			provider: "ollama",
			model: "llama3.2"
		},
		reasoning: {
			provider: "ollama",
			model: "llama3.2"
		},
		deep: {
			provider: "ollama",
			model: "llama3.2"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	},
	"lm-studio": {
		extraction: {
			provider: "openai",
			model: "lm-studio"
		},
		reasoning: {
			provider: "openai",
			model: "lm-studio"
		},
		deep: {
			provider: "openai",
			model: "lm-studio"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	},
	"open-webui": {
		extraction: {
			provider: "openai",
			model: "default"
		},
		reasoning: {
			provider: "openai",
			model: "default"
		},
		deep: {
			provider: "openai",
			model: "default"
		},
		embeddings: {
			provider: "local",
			model: "all-MiniLM-L6-v2"
		}
	}
};
const DEFAULT_PRESET = PRESETS["anthropic"];
function getModelPreset(providerName) {
	return PRESETS[providerName] ?? DEFAULT_PRESET;
}
function formatPresetSummary(preset) {
	return [
		`  Extraction:  ${preset.extraction.provider}/${preset.extraction.model}`,
		`  Reasoning:   ${preset.reasoning.provider}/${preset.reasoning.model}`,
		`  Deep:        ${preset.deep.provider}/${preset.deep.model}`,
		`  Embeddings:  ${preset.embeddings.provider}/${preset.embeddings.model}`
	].join("\n");
}

//#endregion
//#region src/setup/detect-clients.ts
function home() {
	return homedir();
}
function appData() {
	return process.env["APPDATA"] ?? join(home(), "AppData", "Roaming");
}
function claudeDesktopConfigPath() {
	switch (platform()) {
		case "darwin": return join(home(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
		case "win32": return join(appData(), "Claude", "claude_desktop_config.json");
		default: return join(home(), ".config", "Claude", "claude_desktop_config.json");
	}
}
function claudeDesktopDetected(configPath) {
	if (existsSync(configPath) || existsSync(dirname(configPath))) return true;
	if (platform() === "darwin") return existsSync("/Applications/Claude.app");
	return false;
}
function cursorConfigPath() {
	if (platform() === "win32") return join(appData(), "Cursor", "User", "globalStorage", "mcp.json");
	return join(home(), ".cursor", "mcp.json");
}
function cursorDetected(configPath) {
	if (existsSync(configPath) || existsSync(dirname(configPath))) return true;
	if (platform() === "darwin") return existsSync("/Applications/Cursor.app");
	return false;
}
function windsurfConfigPath() {
	if (platform() === "win32") return join(appData(), "Windsurf", "User", "globalStorage", "mcp.json");
	return join(home(), ".codeium", "windsurf", "mcp_config.json");
}
function windsurfDetected(configPath) {
	if (existsSync(configPath) || existsSync(dirname(configPath))) return true;
	if (platform() === "darwin") return existsSync("/Applications/Windsurf.app");
	return false;
}
function detectMcpClients() {
	const claudePath = claudeDesktopConfigPath();
	const cursorPath = cursorConfigPath();
	const windsurfPath = windsurfConfigPath();
	return [
		{
			name: "Claude Desktop",
			configPath: claudePath,
			detected: claudeDesktopDetected(claudePath)
		},
		{
			name: "Cursor",
			configPath: cursorPath,
			detected: cursorDetected(cursorPath)
		},
		{
			name: "Windsurf",
			configPath: windsurfPath,
			detected: windsurfDetected(windsurfPath)
		}
	];
}

//#endregion
//#region src/setup/register-mcp.ts
const SAURIA_MCP_ENTRY = {
	command: "sauria",
	args: ["mcp-server"]
};
function readJsonSafe(filePath) {
	if (!existsSync(filePath)) return {};
	try {
		const raw = readFileSync(filePath, "utf-8");
		const parsed = JSON.parse(raw);
		if (parsed !== null && typeof parsed === "object") return parsed;
	} catch {}
	return {};
}
function writeJsonPretty(filePath, data) {
	const dir = dirname(filePath);
	if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
	writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", "utf-8");
}
function registerMcpInClient(client) {
	if (!client.detected) return {
		client: client.name,
		status: "skipped"
	};
	const config = readJsonSafe(client.configPath);
	if (config.mcpServers?.["sauria"]) return {
		client: client.name,
		status: "already_registered"
	};
	config.mcpServers = {
		...config.mcpServers,
		sauria: SAURIA_MCP_ENTRY
	};
	writeJsonPretty(client.configPath, config);
	return {
		client: client.name,
		status: "registered"
	};
}
function registerMcpInAllClients(clients) {
	return clients.map(registerMcpInClient);
}

//#endregion
//#region src/setup/daemon-service.ts
const LABEL = "ai.sauria.daemon";
function sauriaBinPath() {
	return process.argv[1] ?? "sauria";
}
function generateLaunchdPlist() {
	const bin = sauriaBinPath();
	const logDir = paths.logs;
	return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>${LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>${bin}</string>
        <string>daemon</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>StandardOutPath</key>
    <string>${logDir}/daemon.log</string>
    <key>StandardErrorPath</key>
    <string>${logDir}/daemon.err</string>
    <key>ThrottleInterval</key>
    <integer>30</integer>
</dict>
</plist>`;
}
function generateSystemdUnit() {
	return `[Unit]
Description=Sauria Daemon
After=network.target

[Service]
Type=simple
ExecStart=${sauriaBinPath()} daemon
Restart=on-failure
RestartSec=30
Environment=NODE_ENV=production

[Install]
WantedBy=default.target`;
}
function generateDaemonService() {
	const os = platform();
	if (os === "darwin") {
		const launchAgents = join(homedir(), "Library", "LaunchAgents");
		if (!existsSync(launchAgents)) mkdirSync(launchAgents, { recursive: true });
		const plistPath = join(launchAgents, `${LABEL}.plist`);
		writeFileSync(plistPath, generateLaunchdPlist(), "utf-8");
		return {
			platform: "macOS",
			servicePath: plistPath,
			activationCommand: `launchctl load -w "${plistPath}"`
		};
	}
	if (os === "linux") {
		const systemdDir = join(homedir(), ".config", "systemd", "user");
		if (!existsSync(systemdDir)) mkdirSync(systemdDir, { recursive: true });
		const unitPath = join(systemdDir, "sauria.service");
		writeFileSync(unitPath, generateSystemdUnit(), "utf-8");
		return {
			platform: "Linux",
			servicePath: unitPath,
			activationCommand: "systemctl --user enable --now sauria"
		};
	}
	if (os === "win32") {
		const taskDir = join(paths.home, "service");
		if (!existsSync(taskDir)) mkdirSync(taskDir, { recursive: true });
		const bin = sauriaBinPath();
		const xmlPath = join(taskDir, "sauria-task.xml");
		writeFileSync(xmlPath, `<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>Sauria Daemon</Description>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger><Enabled>true</Enabled></LogonTrigger>
  </Triggers>
  <Actions>
    <Exec>
      <Command>${bin}</Command>
      <Arguments>daemon</Arguments>
    </Exec>
  </Actions>
  <Settings>
    <RestartOnFailure>
      <Interval>PT1M</Interval>
      <Count>3</Count>
    </RestartOnFailure>
  </Settings>
</Task>`, "utf-8");
		return {
			platform: "Windows",
			servicePath: xmlPath,
			activationCommand: `schtasks /create /tn "Sauria" /xml "${xmlPath}"`
		};
	}
	return null;
}

//#endregion
//#region src/auth/validate.ts
async function validateAnthropicCredential(credential) {
	const headers = { "content-type": "application/json" };
	if (isOAuthToken(credential)) headers["authorization"] = `Bearer ${credential}`;
	else headers["x-api-key"] = credential;
	const response = await secureFetch("https://api.anthropic.com/v1/models", {
		method: "GET",
		headers,
		signal: AbortSignal.timeout(1e4)
	});
	if (response.ok) return {
		isValid: true,
		accountInfo: "Anthropic API access confirmed"
	};
	const body = await response.text();
	return {
		isValid: false,
		error: `Anthropic: ${response.status} — ${body.slice(0, 200)}`
	};
}
async function validateOpenAiCredential(apiKey) {
	const response = await secureFetch("https://api.openai.com/v1/models", {
		method: "GET",
		headers: { authorization: `Bearer ${apiKey}` },
		signal: AbortSignal.timeout(1e4)
	});
	if (response.ok) return {
		isValid: true,
		accountInfo: "OpenAI API access confirmed"
	};
	return {
		isValid: false,
		error: `OpenAI: ${response.status}`
	};
}
async function validateGoogleCredential(apiKey) {
	const response = await secureFetch(`https://generativelanguage.googleapis.com/v1/models?key=${encodeURIComponent(apiKey)}`, {
		method: "GET",
		signal: AbortSignal.timeout(1e4)
	});
	if (response.ok) return {
		isValid: true,
		accountInfo: "Google AI access confirmed"
	};
	return {
		isValid: false,
		error: `Google: ${response.status}`
	};
}
async function validateCredential(provider, credential) {
	switch (provider) {
		case "anthropic": return validateAnthropicCredential(credential);
		case "openai":
		case "openrouter":
		case "together":
		case "groq":
		case "mistral": return validateOpenAiCredential(credential);
		case "google": return validateGoogleCredential(credential);
		case "ollama":
		case "local": return {
			isValid: true,
			accountInfo: "Local provider, no validation needed"
		};
		default: return {
			isValid: false,
			error: `Unknown provider: ${provider}`
		};
	}
}

//#endregion
export { formatPresetSummary as a, detectMcpClients as i, generateDaemonService as n, getModelPreset as o, registerMcpInAllClients as r, validateCredential as t };
//# sourceMappingURL=validate-DxDJSvmm.mjs.map