import {
  getSyncRow,
  getSyncedRemoteId,
  upsertSync
} from "./chunk-WU2SRT5G.js";
import {
  injectMcpAuthHeaders
} from "./chunk-DBFPJSOY.js";
import {
  listEntries
} from "./chunk-JU6ELMEH.js";
import {
  getEnvironment
} from "./chunk-GTYDSYTR.js";
import {
  getAgent
} from "./chunk-LGPJPAHU.js";

// src/sync/anthropic.ts
import { createHash } from "crypto";
var ANTHROPIC_BASE = "https://api.anthropic.com";
var BETA_HEADER = "managed-agents-2026-04-01";
function anthropicHeaders(apiKey) {
  return {
    "x-api-key": apiKey,
    "anthropic-version": "2023-06-01",
    "anthropic-beta": BETA_HEADER,
    "content-type": "application/json"
  };
}
async function anthropicPost(path, body, apiKey) {
  const res = await fetch(`${ANTHROPIC_BASE}${path}`, {
    method: "POST",
    headers: anthropicHeaders(apiKey),
    body: JSON.stringify(body)
  });
  if (!res.ok) {
    const err = await res.text().catch(() => "unknown error");
    throw new Error(`Anthropic API ${path} failed (${res.status}): ${err}`);
  }
  return res.json();
}
function hashConfig(obj) {
  return createHash("sha256").update(JSON.stringify(obj)).digest("hex").slice(0, 16);
}
async function syncAgent(agentId, vaultEntries, apiKey) {
  const agent = getAgent(agentId);
  if (!agent) throw new Error(`Agent ${agentId} not found`);
  const agentWithAuth = injectMcpAuthHeaders(agent, vaultEntries);
  const mcpArray = agentWithAuth.mcp_servers ?? [];
  const tools = agentWithAuth.tools && agentWithAuth.tools.length > 0 ? agentWithAuth.tools : [{ type: "agent_toolset_20260401" }];
  const agentConfig = {
    name: agentWithAuth.name,
    model: agentWithAuth.model,
    tools
  };
  if (agentWithAuth.system) agentConfig.system = agentWithAuth.system;
  if (mcpArray.length > 0) agentConfig.mcp_servers = mcpArray;
  if (agentWithAuth.model_config && Object.keys(agentWithAuth.model_config).length > 0) {
    agentConfig.model_config = agentWithAuth.model_config;
  }
  const hash = hashConfig(agentConfig);
  const existing = getSyncRow(agentId, "agent");
  if (existing && existing.config_hash === hash) {
    return existing.remote_id;
  }
  const remote = await anthropicPost("/v1/agents", agentConfig, apiKey);
  upsertSync(agentId, "agent", remote.id, hash);
  console.log(`[sync] agent ${agentId} \u2192 ${remote.id}`);
  return remote.id;
}
async function syncVault(vaultId, agentRemoteId, apiKey) {
  const entries = listEntries(vaultId);
  const MCP_KEY_RE = /^MCP_(AUTH|HEADER)_/i;
  const filteredEntries = entries.filter((e) => !MCP_KEY_RE.test(e.key));
  const hash = hashConfig(filteredEntries.map((e) => e.key).sort());
  const existing = getSyncRow(vaultId, "vault");
  if (existing && existing.config_hash === hash) {
    return existing.remote_id;
  }
  const remote = await anthropicPost("/v1/vaults", {
    display_name: `agentstep-${vaultId.slice(0, 12)}`
  }, apiKey);
  upsertSync(vaultId, "vault", remote.id, hash);
  console.log(`[sync] vault ${vaultId} \u2192 ${remote.id}`);
  return remote.id;
}
async function syncEnvironment(envId, apiKey) {
  const existing = getSyncedRemoteId(envId, "environment");
  if (existing) return existing;
  const env = getEnvironment(envId);
  const remote = await anthropicPost("/v1/environments", {
    name: env?.name ?? `agentstep-env-${envId.slice(0, 12)}`
  }, apiKey);
  upsertSync(envId, "environment", remote.id);
  console.log(`[sync] environment ${envId} \u2192 ${remote.id}`);
  return remote.id;
}
async function syncFile(localFileId, apiKey) {
  const existing = getSyncedRemoteId(localFileId, "file");
  if (existing) return existing;
  const { getFile } = await import("./db/files.js");
  const { readFile: readStoredFile } = await import("./files/storage.js");
  const fileRow = getFile(localFileId);
  if (!fileRow) throw new Error(`File ${localFileId} not found`);
  const data = readStoredFile(fileRow.storage_path);
  const formData = new FormData();
  formData.append("file", new Blob([data], { type: fileRow.content_type }), fileRow.filename);
  const res = await fetch(`${ANTHROPIC_BASE}/v1/files`, {
    method: "POST",
    headers: {
      "x-api-key": apiKey,
      "anthropic-version": "2023-06-01",
      "anthropic-beta": BETA_HEADER
    },
    body: formData
  });
  if (!res.ok) {
    const err = await res.text().catch(() => "unknown error");
    throw new Error(`Anthropic Files API upload failed (${res.status}): ${err}`);
  }
  const remote = await res.json();
  upsertSync(localFileId, "file", remote.id);
  console.log(`[sync] file ${localFileId} \u2192 ${remote.id}`);
  return remote.id;
}
async function syncAndCreateSession(opts) {
  const { agentId, environmentId, vaultIds, sessionId, title, apiKey } = opts;
  const allVaultEntries = [];
  if (vaultIds?.length) {
    for (const vid of vaultIds) {
      allVaultEntries.push(...listEntries(vid));
    }
  }
  const remoteAgentId = await syncAgent(agentId, allVaultEntries, apiKey);
  const remoteVaultIds = [];
  if (vaultIds?.length) {
    for (const vid of vaultIds) {
      const remoteVid = await syncVault(vid, remoteAgentId, apiKey);
      remoteVaultIds.push(remoteVid);
    }
  }
  const remoteEnvId = await syncEnvironment(environmentId, apiKey);
  const remoteResources = [];
  if (sessionId) {
    try {
      const { listResources } = await import("./db/session-resources.js");
      const resources = listResources(sessionId);
      for (const r of resources) {
        if (r.type === "file" && r.file_id) {
          const remoteFileId = await syncFile(r.file_id, apiKey);
          remoteResources.push({
            type: "file",
            file_id: remoteFileId,
            mount_path: r.mount_path ?? void 0
          });
        }
      }
    } catch (err) {
      console.warn("[sync] file sync failed:", err);
    }
  }
  const sessionBody = {
    agent: remoteAgentId,
    environment_id: remoteEnvId
  };
  if (remoteVaultIds.length > 0) sessionBody.vault_ids = remoteVaultIds;
  if (remoteResources.length > 0) sessionBody.resources = remoteResources;
  if (title) sessionBody.title = title;
  const remoteSession = await anthropicPost("/v1/sessions", sessionBody, apiKey);
  console.log(`[sync] session created on Anthropic: ${remoteSession.id}`);
  return { remoteSessionId: remoteSession.id };
}

export {
  syncAgent,
  syncVault,
  syncEnvironment,
  syncAndCreateSession
};
