import { Effect } from "effect"
import type { CustomDep, CustomLoader } from "./provider-types"
import type { Info } from "./provider-schema"
import { useLanguageModel } from "./bundled-providers"
import { cloudLoaders } from "./loader-cloud"
import { platformLoaders } from "./loader-platform"
import { localLoaders } from "./loader-local"
import { iife } from "@/util/iife"

export function custom(dep: CustomDep): Record<string, CustomLoader> {
  return {
    ...localLoaders(dep),
    ...cloudLoaders(dep),
    ...platformLoaders(dep),
    anthropic: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
          },
        },
      }),
    saeeol: Effect.fnUntraced(function* (input: Info) {
      const env = yield* dep.env()
      const hasKey = iife(() => {
        if (input.env.some((item) => env[item])) return true
        return false
      })
      const ok =
        hasKey ||
        Boolean(yield* dep.auth(input.id)) ||
        Boolean((yield* dep.config()).provider?.["saeeol"]?.options?.apiKey)

      if (!ok) {
        for (const [key, value] of Object.entries(input.models)) {
          if (value.cost.input === 0) continue
          delete input.models[key]
        }
      }

      return {
        autoload: Object.keys(input.models).length > 0,
        options: ok ? {} : { apiKey: "public" },
      }
    }),
    openai: () =>
      Effect.succeed({
        autoload: false,
        async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
          return sdk.responses(modelID)
        },
        options: {},
      }),
    xai: () =>
      Effect.succeed({
        autoload: false,
        async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
          return sdk.responses(modelID)
        },
        options: {},
      }),
    llmgateway: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "HTTP-Referer": "https://saeeol.ai/", 
            "X-Title": "SAEEOL", 
            "X-Source": "saeeol", 
          },
        },
      }),
    openrouter: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "HTTP-Referer": "https://saeeol.ai/", 
            "X-Title": "SAEEOL", 
          },
        },
      }),
    nvidia: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "HTTP-Referer": "https://saeeol.ai/", 
            "X-Title": "SAEEOL", 
            "X-BILLING-INVOKE-ORIGIN": "SaeeolCode", 
          },
        },
      }),
    vercel: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "http-referer": "https://saeeol.ai/", 
            "x-title": "SAEEOL", 
          },
        },
      }),
    "google-vertex-anthropic": Effect.fnUntraced(function* () {
      const env = yield* dep.env()
      const project = env["GOOGLE_CLOUD_PROJECT"] ?? env["GCP_PROJECT"] ?? env["GCLOUD_PROJECT"]
      const location = env["GOOGLE_CLOUD_LOCATION"] ?? env["VERTEX_LOCATION"] ?? "global"
      const autoload = Boolean(project)
      if (!autoload) return { autoload: false }
      return {
        autoload: true,
        options: {
          project,
          location,
        },
        async getModel(sdk: any, modelID) {
          const id = String(modelID).trim()
          return sdk.languageModel(id)
        },
      }
    }),
    "sap-ai-core": Effect.fnUntraced(function* () {
      const auth = yield* dep.auth("sap-ai-core")
      const envServiceKey = iife(() => {
        const envAICoreServiceKey = process.env.AICORE_SERVICE_KEY
        if (envAICoreServiceKey) return envAICoreServiceKey
        if (auth?.type === "api") {
          process.env.AICORE_SERVICE_KEY = auth.key
          return auth.key
        }
        return undefined
      })
      const deploymentId = process.env.AICORE_DEPLOYMENT_ID
      const resourceGroup = process.env.AICORE_RESOURCE_GROUP

      return {
        autoload: !!envServiceKey,
        options: envServiceKey ? { deploymentId, resourceGroup } : {},
        async getModel(sdk: any, modelID: string) {
          return sdk(modelID)
        },
      }
    }),
    zenmux: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "HTTP-Referer": "https://saeeol.ai/", 
            "X-Title": "SAEEOL", 
          },
        },
      }),
    cerebras: () =>
      Effect.succeed({
        autoload: false,
        options: {
          headers: {
            "X-Cerebras-3rd-Party-Integration": "SAEEOL", 
          },
        },
      }),
  }
}

// Provider ID lists by category
export const LOCAL_PROVIDERS = ["ollama", "lmstudio", "vllm", "text-generation-webui", "llama.cpp"] as const
export const CUSTOM_PROVIDERS = ["llmgateway", "openrouter", "nvidia", "vercel", "zenmux", "cerebras"] as const
export const CLOUD_PROVIDERS = [
  "anthropic", "openai", "xai", "saeeol",
  "azure", "azure-cognitive-services", "amazon-bedrock",
  "google-vertex", "google-vertex-anthropic", "sap-ai-core",
  "gitlab", "cloudflare-workers-ai", "cloudflare-ai-gateway", "github-copilot",
] as const
