import {
  getUserProfile
} from "./chunk-SK4OB66U.js";
import {
  listCredentialsWithTokens
} from "./chunk-7T3L22TP.js";
import {
  listEntries
} from "./chunk-JU6ELMEH.js";

// src/sessions/secrets.ts
function loadSessionSecrets(vaultIds, userProfileId) {
  let credentialAllowlist = null;
  if (userProfileId) {
    const profile = getUserProfile(userProfileId);
    if (profile && profile.trust_grants.length > 0) {
      credentialAllowlist = new Set(
        profile.trust_grants.map((g) => `${g.vault_id}:${g.credential_id}`)
      );
    }
  }
  const secrets = [];
  for (const vid of vaultIds) {
    for (const entry of listEntries(vid)) {
      secrets.push({ key: entry.key, value: entry.value });
    }
    for (const cred of listCredentialsWithTokens(vid)) {
      if (credentialAllowlist && !credentialAllowlist.has(`${vid}:${cred.id}`)) continue;
      if (cred.auth.mcp_server_url) {
        const serverName = deriveServerName(cred.auth.mcp_server_url);
        if (serverName) {
          const key = `MCP_AUTH_${serverName.toUpperCase().replace(/-/g, "_")}`;
          secrets.push({ key, value: cred.token });
        }
      }
      secrets.push({
        key: `CREDENTIAL_${cred.display_name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`,
        value: cred.token
      });
    }
  }
  return secrets;
}
function deriveServerName(url) {
  try {
    const parsed = new URL(url);
    const host = parsed.hostname;
    const cleaned = host.replace(/^(mcp|api|www)\./, "").replace(/\.(com|io|dev|ai|org|net)$/, "").replace(/\./g, "_");
    return cleaned || null;
  } catch {
    return null;
  }
}

export {
  loadSessionSecrets,
  deriveServerName
};
