import { createLogger } from "../../../src/utils/logger/index.js";
import { init_logger } from "../../../src/utils/logger.js";
import { pickTimeoutMsOrFallback } from "../../../src/media-shared/http/deadline.js";
import { privateNetworkPolicyToSsrfGuardOptions } from "../../../src/media-shared/http/private-network.js";
import { resolveProviderHttpRequestConfig } from "../../../src/media-shared/http/resolve-provider-http-request-config.js";
import { postJsonRequest } from "../../../src/media-shared/http/provider-http.js";
import "../../../src/media-shared/http/index.js";
import { resolveApiKeyForProvider } from "../../../src/providers/auth-runtime/resolve-api-key.js";
import { isProviderApiKeyConfigured } from "../../../src/providers/auth-runtime/is-configured.js";
import "../../../src/providers/auth-runtime/index.js";
//#region extensions/minimax/src/image-generation-provider.ts
/**
* Bundled MiniMax image-generation provider.
*
* Migrated from src/agent/image/generation/minimax-generate.ts. Logic stays
* identical; only the registration pathway moves to the bundled generator.
*/
init_logger();
const log = createLogger("ImageGen:MiniMax");
/**
* MiniMax `POST /v1/image_generation` model names (vendor OpenAPI enum).
* Default: `image-01`. `image-01-live` is the alternate enum value on the same API.
* @see https://platform.minimax.io/docs/api-reference/image-generation-i2i
*/
const MINIMAX_IMAGE_MODELS = ["image-01", "image-01-live"];
const MINIMAX_DEFAULT_IMAGE_MODEL = MINIMAX_IMAGE_MODELS[0];
/** CN region (default for `minimax` ids registered in mainland China). */
const MINIMAX_CN_BASE_URL = "https://api.minimaxi.com";
/** International region (used when the configured key matches `*_INTL_*`). */
const MINIMAX_INTL_BASE_URL = "https://api.minimax.io";
const MINIMAX_IMAGE_UI = {
	baseUrlPresets: [{
		value: MINIMAX_CN_BASE_URL,
		label: "China (api.minimaxi.com)"
	}, {
		value: MINIMAX_INTL_BASE_URL,
		label: "International (api.minimax.io)"
	}],
	baseUrlPresetKind: "minimax"
};
const DEFAULT_TIMEOUT_MS = 12e4;
const MINIMAX_CAPABILITIES = {
	generate: {
		maxCount: 1,
		supportsAspectRatio: true,
		supportsSize: false
	},
	edit: { enabled: false },
	geometry: { aspectRatios: [
		"1:1",
		"16:9",
		"9:16",
		"4:3",
		"3:4"
	] },
	output: { formats: ["jpeg"] }
};
function readMinimaxCfgString(cfg, key) {
	const providers = cfg?.providers;
	if (!providers || typeof providers !== "object") return void 0;
	const entry = providers["minimax"];
	if (!entry || typeof entry !== "object") return void 0;
	const v = entry[key];
	return typeof v === "string" && v.trim() ? v.trim() : void 0;
}
/**
* Resolve MiniMax base URL with CN/Intl auto-detection:
* 1. cfg.providers.minimax.baseUrl
* 2. MINIMAX_BASE_URL env
* 3. Auto: when MINIMAX_INTL_API_KEY env is the only key present, default to Intl;
*    otherwise CN.
*/
function resolveMinimaxBaseUrl(req) {
	const fromCfg = readMinimaxCfgString(req.cfg, "baseUrl");
	if (fromCfg) return fromCfg.replace(/\/+$/, "");
	const fromEnv = process.env.MINIMAX_BASE_URL?.trim();
	if (fromEnv) return fromEnv.replace(/\/+$/, "");
	if (process.env.MINIMAX_INTL_API_KEY && !process.env.MINIMAX_API_KEY) return MINIMAX_INTL_BASE_URL;
	return MINIMAX_CN_BASE_URL;
}
function resolveMinimaxImageUrl(req) {
	return `${resolveMinimaxBaseUrl(req)}/v1/image_generation`;
}
/** Map tool size (e.g. `1024x1024`) to the closest MiniMax-supported aspect ratio. */
function mapSizeToMinimaxAspectRatio(size) {
	if (!size?.trim()) return "1:1";
	const m = /^(\d+)\s*[xX]\s*(\d+)$/.exec(size.trim());
	if (!m) return "1:1";
	const w = Number(m[1]);
	const h = Number(m[2]);
	if (!Number.isFinite(w) || !Number.isFinite(h) || h === 0) return "1:1";
	const ratio = w / h;
	const candidates = [
		{
			ar: "1:1",
			r: 1
		},
		{
			ar: "16:9",
			r: 16 / 9
		},
		{
			ar: "9:16",
			r: 9 / 16
		},
		{
			ar: "4:3",
			r: 4 / 3
		},
		{
			ar: "3:4",
			r: 3 / 4
		}
	];
	let best = candidates[0];
	let bestDiff = Math.abs(ratio - best.r);
	for (const c of candidates.slice(1)) {
		const d = Math.abs(ratio - c.r);
		if (d < bestDiff) {
			best = c;
			bestDiff = d;
		}
	}
	return best.ar;
}
async function generateMinimaxImages(params) {
	const { req, apiKey } = params;
	if (req.inputImages && req.inputImages.length > 0) throw new Error("Image-to-image is not supported for MiniMax in this build");
	const model = req.model?.trim() || MINIMAX_DEFAULT_IMAGE_MODEL;
	const aspectRatio = req.aspectRatio?.trim() || mapSizeToMinimaxAspectRatio(req.size);
	const url = resolveMinimaxImageUrl(req);
	const httpDefaults = resolveProviderHttpRequestConfig({
		providerId: "minimax",
		cfg: req.cfg,
		fallbackTimeoutMs: DEFAULT_TIMEOUT_MS
	});
	log.debug({
		providerId: "minimax",
		model,
		url,
		aspectRatio,
		phase: "request"
	}, "MiniMax image generation request");
	const rawText = await (await postJsonRequest(url, {
		label: "minimax",
		timeoutMs: pickTimeoutMsOrFallback(req.timeoutMs, httpDefaults.timeoutMs, DEFAULT_TIMEOUT_MS),
		signal: req.signal,
		body: {
			model,
			prompt: req.prompt,
			aspect_ratio: aspectRatio,
			response_format: "base64"
		},
		headers: {
			...httpDefaults.headers,
			authorization: `Bearer ${apiKey}`
		},
		...privateNetworkPolicyToSsrfGuardOptions()
	})).text();
	let data;
	try {
		data = JSON.parse(rawText);
	} catch {
		throw new Error(`MiniMax returned non-JSON: ${rawText.slice(0, 240)}`);
	}
	const code = data.base_resp?.status_code;
	if (code !== void 0 && code !== 0) throw new Error(`MiniMax: ${code}: ${data.base_resp?.status_msg ?? "request failed"}`.trim());
	const imageBase64List = data.data?.image_base64 ?? [];
	if (imageBase64List.length === 0) throw new Error("MiniMax returned no images");
	return {
		images: imageBase64List.map((b64, index) => ({
			buffer: Buffer.from(b64, "base64"),
			mimeType: "image/jpeg",
			fileName: `image-${index + 1}.jpg`
		})),
		model
	};
}
function buildMinimaxImageGenerationProvider() {
	return {
		id: "minimax",
		label: "MiniMax",
		defaultModel: MINIMAX_DEFAULT_IMAGE_MODEL,
		models: [...MINIMAX_IMAGE_MODELS],
		capabilities: MINIMAX_CAPABILITIES,
		ui: MINIMAX_IMAGE_UI,
		isConfigured: (ctx) => isProviderApiKeyConfigured({
			providerId: "minimax",
			cfg: ctx.cfg
		}),
		async generateImage(req) {
			const apiKey = resolveApiKeyForProvider({
				providerId: "minimax",
				cfg: req.cfg
			});
			if (!apiKey) throw new Error("MiniMax API key missing (MINIMAX_API_KEY or providers.minimax.apiKey)");
			return generateMinimaxImages({
				req,
				apiKey
			});
		}
	};
}
//#endregion
export { MINIMAX_DEFAULT_IMAGE_MODEL, MINIMAX_IMAGE_MODELS, buildMinimaxImageGenerationProvider, generateMinimaxImages, mapSizeToMinimaxAspectRatio, resolveMinimaxBaseUrl };

//# sourceMappingURL=image-generation-provider.js.map