import { CredentialResolver, init_credentials } from "../../auth/credentials.js";
import { anthropicOAuthProvider } from "../../auth/oauth/anthropic.js";
import { init_providers, isProviderConfigured } from "../../providers/index.js";
import { minimaxOAuthProvider } from "../../auth/oauth/minimax.js";
import { minimaxCnOAuthProvider } from "../../auth/oauth/minimax-cn.js";
import { kimiCodingOAuthProvider } from "../../auth/oauth/kimi-coding.js";
import { githubCopilotOAuthProvider } from "../../auth/oauth/github-copilot.js";
import { geminiCliOAuthProvider } from "../../auth/oauth/vendor-pi-google/google-gemini-cli.js";
import { antigravityOAuthProvider } from "../../auth/oauth/vendor-pi-google/google-antigravity.js";
import { openaiCodexOAuthProvider } from "../../auth/oauth/openai-codex.js";
import "../../auth/oauth/index.js";
import { Hono } from "hono";
//#region src/gateway/hono/oauth.ts
/**
* OAuth HTTP Handler
* 
* Provides HTTP endpoints for OAuth login flow.
*/
init_credentials();
init_providers();
const OAUTH_PROVIDERS = {
	"kimi-coding": kimiCodingOAuthProvider,
	"minimax": minimaxOAuthProvider,
	"minimax-cn": minimaxCnOAuthProvider,
	"anthropic": anthropicOAuthProvider,
	"github-copilot": githubCopilotOAuthProvider,
	"google-gemini-cli": geminiCliOAuthProvider,
	"google-antigravity": antigravityOAuthProvider,
	"openai-codex": openaiCodexOAuthProvider
};
const oauthCredentialsCache = /* @__PURE__ */ new Map();
function getOAuthCredentialsFromCache(provider) {
	return oauthCredentialsCache.get(provider);
}
function setOAuthCredentialsToCache(provider, creds) {
	oauthCredentialsCache.set(provider, creds);
}
function deleteOAuthCredentialsFromCache(provider) {
	oauthCredentialsCache.delete(provider);
}
/** No-op: OAuth tokens live on disk under auth paths; cache is populated during login. */
function loadOAuthCredentialsToCache(_service) {}
function createOAuthHandler(_service) {
	const oauth = new Hono();
	/**
	* POST /api/auth/oauth/start
	* Start OAuth flow for a provider
	*/
	oauth.post("/start", async (c) => {
		const { provider } = await c.req.json().catch(() => ({}));
		if (!provider) return c.json({ error: "Provider is required" }, 400);
		const oauthProvider = OAUTH_PROVIDERS[provider];
		if (!oauthProvider) return c.json({ error: `Unknown OAuth provider: ${provider}` }, 400);
		try {
			let authResult = null;
			let manualCodeRequested = false;
			const credentials = await oauthProvider.login({
				onAuth: (auth) => {
					authResult = {
						url: auth.url,
						instructions: auth.instructions
					};
				},
				onPrompt: async (prompt) => {
					authResult = {
						message: prompt.message,
						deviceCode: prompt.deviceCode,
						verificationUri: prompt.verificationUri
					};
					return prompt.deviceCode || "";
				},
				onProgress: (message) => {
					console.log("OAuth progress:", message);
				},
				onManualCodeInput: async () => {
					manualCodeRequested = true;
					return "";
				}
			});
			setOAuthCredentialsToCache(provider, credentials);
			const apiKey = oauthProvider.getApiKey(credentials);
			await new CredentialResolver().saveApiKey(provider, apiKey, { profileName: "default" });
			return c.json({
				ok: true,
				payload: {
					success: true,
					provider,
					message: "OAuth login successful",
					expires: credentials.expires,
					authUrl: authResult?.url,
					deviceCode: authResult?.deviceCode,
					verificationUri: authResult?.verificationUri,
					instructions: authResult?.instructions,
					usesCallbackServer: oauthProvider.usesCallbackServer ?? false,
					manualCodeRequested
				}
			});
		} catch (err) {
			console.error("OAuth login error:", err);
			return c.json({ error: err instanceof Error ? err.message : "OAuth login failed" }, 500);
		}
	});
	/**
	* GET /api/auth/oauth/:provider
	* Check OAuth status for a provider
	*/
	oauth.get("/:provider", async (c) => {
		const provider = c.req.param("provider");
		const credentials = getOAuthCredentialsFromCache(provider);
		const configured = await isProviderConfigured(provider);
		return c.json({
			ok: true,
			payload: {
				configured: configured || !!credentials,
				expires: credentials?.expires
			}
		});
	});
	/**
	* DELETE /api/auth/oauth/:provider
	* Revoke OAuth credentials
	*/
	oauth.delete("/:provider", async (c) => {
		deleteOAuthCredentialsFromCache(c.req.param("provider"));
		return c.json({ ok: true });
	});
	/**
	* GET /api/auth/oauth
	* List available OAuth providers
	*/
	oauth.get("/", (c) => {
		const result = Object.entries(OAUTH_PROVIDERS).map(([id, p]) => ({
			id,
			name: p.name
		}));
		return c.json({
			ok: true,
			payload: { providers: result }
		});
	});
	return oauth;
}
//#endregion
export { createOAuthHandler, loadOAuthCredentialsToCache };

//# sourceMappingURL=oauth.js.map