import { api } from "@/lib/api-client";

/**
 * AI provider & API-key settings client.
 *
 * Backed by `backend/custom_addons/encoach_ai/controllers/ai_settings_controller.py`
 * (`/api/ai/settings/providers`). API keys are write-only — the GET response
 * only ever exposes `<key>_set: boolean` markers, never the key itself.
 *
 * Provider switches take effect on the very next request (no caching),
 * so the LangGraph runtime instantly picks up the new selection.
 */

export type CapabilityKey = "text" | "image" | "audio" | "video";
export type ProviderKind = "paid" | "free" | "auto";

export interface ProviderOption {
  value: string;
  label: string;
  kind: ProviderKind;
}

export interface CapabilityState {
  active: string;
  options: ProviderOption[];
  paid_with_credentials: string[];
}

export interface AISettingsState {
  providers: Record<CapabilityKey, CapabilityState>;
  /** Boolean markers — `true` means a value is stored, never the value itself. */
  keys_set: Record<string, boolean>;
  /** Plain (non-secret) parameters, e.g. region, model name. */
  plain: Record<string, string>;
}

export interface ProviderTestResult {
  capability: CapabilityKey;
  active: string;
  chain: { provider: string; ok: boolean; note: string }[];
}

export interface AISettingsPatchPayload {
  /** Active provider per capability. */
  providers?: Partial<Record<CapabilityKey, string>>;
  /**
   * API keys keyed by short name (`openai_api_key`, `aws_access_key`,
   * `aws_secret_key`, `aws_region`, `elevenlabs_api_key`,
   * `gptzero_api_key`, `paymob_api_key`, `paymob_integration_id`,
   * `paymob_iframe_id`, `paymob_hmac_secret`).
   *
   * - Sending an empty string clears the key.
   * - Omitting the field leaves it unchanged.
   */
  keys?: Record<string, string>;
  /** Plain (non-secret) values like `aws_region`, `openai_model`. */
  plain?: Record<string, string>;
}

export const aiSettingsService = {
  async get(): Promise<AISettingsState> {
    const resp = await api.get<{ data: AISettingsState }>(
      "/ai/settings/providers",
    );
    return resp.data;
  },

  async update(payload: AISettingsPatchPayload): Promise<AISettingsState> {
    const resp = await api.patch<{ data: AISettingsState }>(
      "/ai/settings/providers",
      payload,
    );
    return resp.data;
  },

  async test(capability: CapabilityKey): Promise<ProviderTestResult> {
    return api.post<ProviderTestResult>(
      "/ai/settings/providers/test",
      { capability },
    );
  },
};
