import path from "node:path";
import { z } from "zod";
import { loadPersistedConfig } from "./persisted-config.js";
import { AgentProviderSchema } from "./agent/provider-manifest.js";
import { resolveSpeechConfig } from "./speech/speech-config-resolver.js";
import { mergeAllowedHosts, parseAllowedHostsEnv, } from "./allowed-hosts.js";
const DEFAULT_PORT = 6767;
// Defaults can be overridden via SEAWORK_RELAY_ENDPOINT and SEAWORK_APP_BASE_URL env vars
// or persisted config. Replace these with your own domain after Cloudflare setup.
const DEFAULT_RELAY_ENDPOINT = "relay.seawork.ai:443";
const DEFAULT_APP_BASE_URL = "https://app.seawork.ai";
function parseBooleanEnv(value) {
    if (value === undefined) {
        return undefined;
    }
    const normalized = value.trim().toLowerCase();
    if (["1", "true", "yes", "on"].includes(normalized)) {
        return true;
    }
    if (["0", "false", "no", "off"].includes(normalized)) {
        return false;
    }
    return undefined;
}
const OptionalVoiceLlmProviderSchema = z
    .union([z.string(), z.null(), z.undefined()])
    .transform((value) => typeof value === "string" ? value.trim().toLowerCase() : null)
    .pipe(z.union([AgentProviderSchema, z.null()]));
function parseOptionalVoiceLlmProvider(value) {
    const parsed = OptionalVoiceLlmProviderSchema.safeParse(value);
    return parsed.success ? parsed.data : null;
}
export function loadConfig(seaworkHome, options) {
    const env = options?.env ?? process.env;
    const persisted = loadPersistedConfig(seaworkHome);
    // SEAWORK_LISTEN can be:
    // - host:port (TCP)
    // - /path/to/socket (Unix socket)
    // - unix:///path/to/socket (Unix socket)
    // Default is TCP at 127.0.0.1:6767
    const listen = options?.cli?.listen ??
        env.SEAWORK_LISTEN ??
        persisted.daemon?.listen ??
        `127.0.0.1:${env.PORT ?? DEFAULT_PORT}`;
    const envCorsOrigins = env.SEAWORK_CORS_ORIGINS
        ? env.SEAWORK_CORS_ORIGINS.split(",").map((s) => s.trim())
        : [];
    const persistedCorsOrigins = persisted.daemon?.cors?.allowedOrigins ?? [];
    const allowedHosts = mergeAllowedHosts([
        persisted.daemon?.allowedHosts,
        parseAllowedHostsEnv(env.SEAWORK_ALLOWED_HOSTS),
        options?.cli?.allowedHosts,
    ]);
    const mcpEnabled = options?.cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true;
    const mcpInjectIntoAgents = options?.cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false;
    const relayEnabled = options?.cli?.relayEnabled ??
        parseBooleanEnv(env.SEAWORK_RELAY_ENABLED) ??
        persisted.daemon?.relay?.enabled ??
        true;
    const relayEndpoint = env.SEAWORK_RELAY_ENDPOINT ?? persisted.daemon?.relay?.endpoint ?? DEFAULT_RELAY_ENDPOINT;
    const relayPublicEndpoint = env.SEAWORK_RELAY_PUBLIC_ENDPOINT ?? persisted.daemon?.relay?.publicEndpoint ?? relayEndpoint;
    const appBaseUrl = env.SEAWORK_APP_BASE_URL ?? persisted.app?.baseUrl ?? DEFAULT_APP_BASE_URL;
    const { openai, speech } = resolveSpeechConfig({
        seaworkHome,
        env,
        persisted,
    });
    const envVoiceLlmProvider = parseOptionalVoiceLlmProvider(env.SEAWORK_VOICE_LLM_PROVIDER);
    const persistedVoiceLlmProvider = parseOptionalVoiceLlmProvider(persisted.features?.voiceMode?.llm?.provider);
    const voiceLlmProvider = envVoiceLlmProvider ?? persistedVoiceLlmProvider ?? null;
    const voiceLlmProviderExplicit = envVoiceLlmProvider !== null || persistedVoiceLlmProvider !== null;
    const voiceLlmModel = persisted.features?.voiceMode?.llm?.model ?? null;
    return {
        listen,
        seaworkHome,
        corsAllowedOrigins: Array.from(new Set([
            // Always allow the hosted web app regardless of persisted config
            "https://app.seawork.ai",
            ...persistedCorsOrigins,
            ...envCorsOrigins,
        ].filter((s) => s.length > 0))),
        allowedHosts,
        mcpEnabled,
        mcpInjectIntoAgents,
        mcpDebug: env.MCP_DEBUG === "1",
        agentStoragePath: path.join(seaworkHome, "agents"),
        staticDir: "public",
        agentClients: {},
        relayEnabled,
        relayEndpoint,
        relayPublicEndpoint,
        appBaseUrl,
        openai,
        speech,
        voiceLlmProvider,
        voiceLlmProviderExplicit,
        voiceLlmModel,
        agentProviderSettings: persisted.agents?.providers,
    };
}
//# sourceMappingURL=config.js.map