import {
  resolveAnthropicKey
} from "../chunk-ZXNWEMLX.js";
import {
  resolveRemoteSessionId
} from "../chunk-WU2SRT5G.js";
import "../chunk-2KDG4PKE.js";
import {
  createFile
} from "../chunk-BGBPOR4J.js";
import {
  isProxied
} from "../chunk-DZIKCTP6.js";
import {
  onAfterCommit
} from "../chunk-4NRHKTBW.js";
import "../chunk-JU6ELMEH.js";
import {
  getSession
} from "../chunk-SEGKFEG5.js";
import "../chunk-UU3ECGO5.js";
import "../chunk-AIBH32FN.js";
import "../chunk-YPXI7Q2M.js";
import "../chunk-LH3NEWMT.js";
import "../chunk-LGPJPAHU.js";
import "../chunk-X27B5TCC.js";
import "../chunk-2MAQ6JFL.js";
import "../chunk-F4WUVOLE.js";
import "../chunk-HFDLUBWN.js";
import "../chunk-RII4M3J2.js";
import "../chunk-DDJOPRB7.js";
import {
  getDb,
  init_client
} from "../chunk-TLEKKGH7.js";
import "../chunk-KBM3MISV.js";
import "../chunk-J5Z5DSH4.js";
import "../chunk-2ESYSVXG.js";

// src/sync/file-sync.ts
init_client();
var ANTHROPIC_API = "https://api.anthropic.com";
var BETA_HEADER = "managed-agents-2026-04-01,files-api-2025-04-14";
async function syncRemoteFiles(sessionId) {
  const resolved = resolveAnthropicKey({ sessionId });
  if (!resolved) return;
  const remoteSessionId = resolveRemoteSessionId(sessionId);
  const res = await fetch(
    `${ANTHROPIC_API}/v1/files?scope_id=${remoteSessionId}`,
    {
      headers: {
        "x-api-key": resolved.value,
        "anthropic-version": "2023-06-01",
        "anthropic-beta": BETA_HEADER
      },
      signal: AbortSignal.timeout(1e4)
    }
  );
  if (!res.ok) {
    console.warn(`[file-sync] Anthropic files list failed: ${res.status}`);
    return;
  }
  const body = await res.json();
  const files = body.data;
  if (!files || files.length === 0) return;
  const db = getDb();
  for (const f of files) {
    const storagePath = `remote:${f.id}`;
    const existing = db.prepare(`SELECT id FROM files WHERE storage_path = ?`).get(storagePath);
    if (existing) continue;
    createFile({
      filename: f.filename ?? "output",
      size: f.size ?? 0,
      content_type: f.mime_type ?? f.content_type ?? "application/octet-stream",
      storage_path: storagePath,
      scope: { type: "session", id: sessionId }
    });
  }
}
function installFileSyncHook() {
  return onAfterCommit((sessionId, row) => {
    if (row.type !== "session.status_idle") return;
    if (!isProxied(sessionId)) return;
    if (!getSession(sessionId)) return;
    void syncRemoteFiles(sessionId).catch((err) => {
      console.warn("[file-sync] failed:", err);
    });
  });
}
export {
  installFileSyncHook
};
