import { j as json } from './exports-D1quPX8S.js';
import { ae as importHostOpenCode, j as authJsonPath, R as detectHostOpenCode, H as createLogger, p as checkDocker, n as buildComposeOptions } from './src-CidJbygh.js';
import { g as getState } from './state-fxN45gBp.js';
import { o as opencodeFetch } from './http-D8YVIqJa.js';
import { c as composeRestart } from './docker-CTjWsP_Q.js';
import { existsSync, readFileSync } from 'node:fs';
import './utils-BSRjJDrZ.js';
import './chunk-CLZ62Ad-.js';
import 'node:module';
import './provider-constants-DPrj3yBX.js';
import './dist-DOFcG0Zp.js';
import 'node:path';
import 'buffer';
import 'fs';
import 'path';
import 'node:child_process';
import 'node:url';
import 'node:crypto';
import 'events';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'assert';
import 'zlib';
import 'node:assert';
import 'node:fs/promises';
import 'node:os';
import './endpoints-UdQGgKsR.js';

//#region src/routes/api/setup/import-host/+server.ts
/**
* POST /api/setup/import-host
*
* Setup-phase equivalent of POST /admin/providers/import-host.
* No admin auth required — the admin token hasn't been written yet during setup.
*
* Copies host OpenCode config + auth into OP_HOME and live-pushes credentials
* to the running OpenCode subprocess so providers appear connected immediately.
*/
var logger = createLogger("setup:import-host");
async function pushAuthToOpenCode(authPath) {
	let raw;
	try {
		raw = JSON.parse(readFileSync(authPath, "utf-8"));
	} catch (err) {
		return {
			pushed: [],
			errors: [{
				provider: "*",
				error: `Could not read auth.json: ${err instanceof Error ? err.message : String(err)}`
			}]
		};
	}
	if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {
		pushed: [],
		errors: [{
			provider: "*",
			error: "auth.json is not a JSON object"
		}]
	};
	const pushed = [];
	const errors = [];
	for (const [providerId, value] of Object.entries(raw)) {
		if (providerId === "anthropic") continue;
		try {
			await opencodeFetch(`/auth/${encodeURIComponent(providerId)}`, {
				method: "PUT",
				body: JSON.stringify(value)
			});
			pushed.push(providerId);
		} catch (err) {
			errors.push({
				provider: providerId,
				error: err instanceof Error ? err.message : String(err)
			});
		}
	}
	return {
		pushed,
		errors
	};
}
/** Restart provider-consuming services so they re-read imported startup config. */
async function restartProviderConsumers(state) {
	const services = ["assistant"];
	if (!(await checkDocker()).ok) return {
		restarted: [],
		failed: services.map((s) => ({
			service: s,
			error: "docker unavailable"
		}))
	};
	const opts = buildComposeOptions(state);
	const restarted = [];
	const failed = [];
	for (const service of services) try {
		const r = await composeRestart([service], opts);
		if (r.ok) restarted.push(service);
		else failed.push({
			service,
			error: r.stderr || `exit ${r.code}`
		});
	} catch (err) {
		failed.push({
			service,
			error: err instanceof Error ? err.message : String(err)
		});
	}
	return {
		restarted,
		failed
	};
}
/** Read the provider ids present in an auth.json, ignoring read/parse errors. */
function providerIdsFromAuth(authPath) {
	try {
		const raw = JSON.parse(readFileSync(authPath, "utf-8"));
		if (raw && typeof raw === "object" && !Array.isArray(raw)) return Object.keys(raw);
	} catch {}
	return [];
}
var POST = async () => {
	const state = getState();
	let result;
	try {
		result = importHostOpenCode(state, { overwriteConflicts: false });
	} catch (err) {
		return json({
			ok: false,
			error: `Could not copy host OpenCode config: ${err instanceof Error ? err.message : String(err)}`
		}, { status: 500 });
	}
	const importedAuthPath = authJsonPath(state);
	let importedProviderIds = [];
	if (result.imported.credentials > 0 || existsSync(importedAuthPath)) {
		const fromDestination = providerIdsFromAuth(importedAuthPath);
		if (fromDestination.length > 0) importedProviderIds = fromDestination;
		else if (result.imported.credentials > 0) {
			const hostStatus = detectHostOpenCode();
			const hostFallback = hostStatus.authPath ? providerIdsFromAuth(hostStatus.authPath) : [];
			logger.warn("post-copy auth.json read returned no providers despite credentials being reported; falling back to host auth.json", {
				importedAuthPath,
				importedCredentials: result.imported.credentials,
				fallbackCount: hostFallback.length
			});
			importedProviderIds = hostFallback;
		}
	}
	const conflictProviders = result.conflicts;
	const authPathToUse = existsSync(importedAuthPath) ? importedAuthPath : null;
	let pushResult = {
		pushed: [],
		errors: []
	};
	if (authPathToUse) pushResult = await pushAuthToOpenCode(authPathToUse);
	const restart = await restartProviderConsumers(state);
	return json({
		ok: true,
		imported: result.imported,
		importedProviders: importedProviderIds,
		conflicts: result.conflicts.length,
		conflictProviders,
		livePushed: pushResult.pushed.length,
		pushedProviders: pushResult.pushed,
		errors: pushResult.errors,
		restarted: restart.restarted,
		restartFailed: restart.failed
	});
};

export { POST };
//# sourceMappingURL=_server.ts-BlD-xqHX.js.map
