export type Permission = 'public' | 'basic' | 'creat' | 'power' | 'manager';

export interface AuthUser {
  sub: string;
  username: string;
  role?: string[];
  tenantId?: string | null;
  gatewayTenantId?: string;
  tenantKey?: string;
  sso_id?: string;
  source?: 'gateway' | 'server-main' | 'sync' | string;
  gatewayUserId?: string;
  userGroupId?: string;
  userGroupKey?: string;
  userGroupKeys?: string[];
  apiKeyId?: string;
  apiKeySecret?: string;
  apiKeyName?: string;
  apiKeyPrefix?: string;
}

export interface AuthResponse {
  accessToken: string;
  tokenType: 'Bearer';
  expiresIn: number;
  user: AuthUser;
}

export interface LocalRegisterRequest {
  username: string;
  email?: string;
  password: string;
  displayName?: string;
  invitationCode?: string;
}

export interface LocalLoginRequest {
  account: string;
  password: string;
}

export interface GatewayInvitation {
  id: string;
  inviteCode: string;
  maxUses?: number;
  usedCount: number;
  expiresAt?: string;
  status: 'active' | 'disabled' | 'expired' | string;
  metadata?: Record<string, unknown>;
  createdBy?: string;
  createdAt: string;
  updatedAt: string;
}

export interface IntegrationPlatform {
  id: string;
  provider: string;
  platformKey: string;
  name: string;
  internalName?: string;
  baseUrl?: string;
  authType: string;
  status: 'enabled' | 'disabled' | string;
  priority: number;
  dynamicPriority?: number;
  effectivePriority?: number;
  defaultPricingMode: PricingMode;
  defaultDiscountFactor: number;
  pricingRuleSetId?: string;
  config?: Record<string, unknown>;
  credentialsPreview?: Record<string, unknown>;
  retryPolicy?: RateLimitPolicy | Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  cooldownUntil?: string;
  createdAt: string;
  updatedAt: string;
}

export type PricingMode = 'inherit' | 'inherit_discount' | 'custom';

export type RateLimitMetric =
  | 'tpm_total'
  | 'tpm_input'
  | 'tpm_output'
  | 'rpm'
  | 'rps'
  | 'concurrent'
  | 'queue_size';

export interface CatalogProvider {
  id: string;
  providerKey: string;
  code: string;
  displayName: string;
  providerType: string;
  iconPath?: string;
  defaultBaseUrl?: string;
  defaultAuthType?: string;
  source?: 'gateway' | 'server-main' | 'sync' | 'server-main.integration-platform' | string;
  capabilitySchema?: Record<string, unknown>;
  defaultRateLimitPolicy?: RateLimitPolicy;
  metadata?: Record<string, unknown>;
  status: 'active' | 'deprecated' | 'hidden' | string;
  createdAt: string;
  updatedAt: string;
}

export interface CatalogProviderUpsertRequest {
  providerKey: string;
  code?: string;
  displayName: string;
  providerType?: string;
  iconPath?: string;
  defaultBaseUrl?: string;
  defaultAuthType?: string;
  source?: 'gateway' | 'server-main' | 'sync' | 'server-main.integration-platform' | string;
  capabilitySchema?: Record<string, unknown>;
  defaultRateLimitPolicy?: RateLimitPolicy;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'deprecated' | 'hidden' | string;
}

export interface BaseModelCatalogItem {
  id: string;
  providerKey: string;
  canonicalModelKey: string;
  invocationName: string;
  providerModelName: string;
  modelType: string[];
  /** @deprecated Use invocationName. */
  modelAlias: string;
  displayName: string;
  legacyAliases?: string[];
  referenceCount: number;
  capabilities?: Record<string, unknown>;
  baseBillingConfig?: BillingConfig;
  defaultRateLimitPolicy?: RateLimitPolicy;
  pricingRuleSetId?: string;
  runtimePolicySetId?: string;
  runtimePolicyOverride?: RuntimePolicyOverride;
  metadata?: Record<string, unknown>;
  catalogType?: 'system' | 'custom' | string;
  defaultSnapshot?: Record<string, unknown>;
  customizedAt?: string;
  pricingVersion: number;
  status: 'active' | 'deprecated' | 'hidden' | string;
  createdAt: string;
  updatedAt: string;
}

export interface BaseModelUpsertRequest {
  providerKey: string;
  canonicalModelKey?: string;
  invocationName?: string;
  providerModelName: string;
  modelType: string[];
  modelAlias?: string;
  displayName?: string;
  legacyAliases?: string[];
  capabilities?: Record<string, unknown>;
  baseBillingConfig?: BillingConfig;
  defaultRateLimitPolicy?: RateLimitPolicy;
  pricingRuleSetId?: string;
  runtimePolicySetId?: string;
  runtimePolicyOverride?: RuntimePolicyOverride;
  metadata?: Record<string, unknown>;
  catalogType?: 'system' | 'custom' | string;
  defaultSnapshot?: Record<string, unknown>;
  pricingVersion?: number;
  status?: 'active' | 'deprecated' | 'hidden' | string;
}

export interface PricingRule {
  id: string;
  ruleSetId?: string;
  ruleKey: string;
  displayName: string;
  scopeType: 'base_model' | 'platform' | 'platform_model' | string;
  scopeId?: string;
  resourceType:
    | 'text_input'
    | 'text_output'
    | 'text_total'
    | 'image'
    | 'video'
    | 'audio'
    | 'music'
    | 'digital_human'
    | 'model'
    | string;
  unit: '1k_tokens' | 'image' | '5s' | 'second' | 'character_1k' | 'item' | string;
  basePrice: number;
  isFree: boolean;
  currency: 'resource' | 'credit' | 'cny' | 'usd' | string;
  baseWeight?: Record<string, unknown>;
  dynamicWeight?: Record<string, unknown>;
  calculatorType: 'token_usage' | 'unit_weight' | 'duration_weight' | string;
  dimensionSchema?: Record<string, unknown>;
  formulaConfig?: Record<string, unknown>;
  priority: number;
  status: 'active' | 'deprecated' | 'hidden' | string;
  metadata?: Record<string, unknown>;
  effectiveFrom?: string;
  effectiveTo?: string;
  createdAt: string;
  updatedAt: string;
}

export interface PricingRuleInput {
  ruleKey?: string;
  displayName?: string;
  resourceType: string;
  unit: string;
  basePrice: number;
  isFree?: boolean;
  currency?: string;
  baseWeight?: Record<string, unknown>;
  dynamicWeight?: Record<string, unknown>;
  calculatorType?: 'token_usage' | 'unit_weight' | 'duration_weight' | string;
  dimensionSchema?: Record<string, unknown>;
  formulaConfig?: Record<string, unknown>;
  priority?: number;
  status?: 'active' | 'deprecated' | 'hidden' | string;
  metadata?: Record<string, unknown>;
  effectiveFrom?: string;
  effectiveTo?: string;
}

export interface PricingRuleSet {
  id: string;
  ruleSetKey: string;
  name: string;
  description?: string;
  category: 'default' | 'custom' | 'provider' | 'model' | string;
  currency: 'resource' | 'credit' | 'cny' | 'usd' | string;
  status: 'active' | 'deprecated' | 'hidden' | string;
  metadata?: Record<string, unknown>;
  rules?: PricingRule[];
  createdAt: string;
  updatedAt: string;
}

export interface PricingRuleSetUpsertRequest {
  ruleSetKey: string;
  name: string;
  description?: string;
  category?: string;
  currency?: string;
  status?: 'active' | 'deprecated' | 'hidden' | string;
  metadata?: Record<string, unknown>;
  rules: PricingRuleInput[];
}

export interface RuntimePolicySet {
  id: string;
  policyKey: string;
  name: string;
  description?: string;
  rateLimitPolicy?: RateLimitPolicy | Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  autoDisablePolicy?: Record<string, unknown>;
  degradePolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status: 'active' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export interface RuntimePolicySetUpsertRequest {
  policyKey: string;
  name: string;
  description?: string;
  rateLimitPolicy?: RateLimitPolicy | Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  autoDisablePolicy?: Record<string, unknown>;
  degradePolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | string;
}

export type RunnerFailoverAction = 'stop' | 'next' | 'cooldown_and_next' | 'demote_and_next' | 'disable_and_next';
export type RunnerFailoverTarget = 'model' | 'platform';

export interface RunnerFailoverActionRule {
  enabled?: boolean;
  categories?: string[];
  codes?: string[];
  errorCodes?: string[];
  statusCodes?: number[];
  keywords?: string[];
  action: RunnerFailoverAction;
  target?: RunnerFailoverTarget;
  cooldownSeconds?: number;
  demoteSteps?: number;
}

export interface RunnerFailoverPolicy {
  enabled?: boolean;
  maxPlatforms?: number;
  maxDurationSeconds?: number;
  actionRules?: RunnerFailoverActionRule[];
  legacyFieldsDeprecated?: boolean;
  deprecatedFields?: string[];
  replacedBy?: 'actionRules' | string;
  [key: string]: unknown;
}

export interface RuntimePolicyOverride {
  rateLimitPolicy?: RateLimitPolicy | Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  failoverPolicy?: RunnerFailoverPolicy;
  autoDisablePolicy?: Record<string, unknown>;
  degradePolicy?: Record<string, unknown>;
}

export interface GatewayRunnerPolicy {
  id: string;
  policyKey: string;
  name: string;
  description?: string;
  failoverPolicy?: RunnerFailoverPolicy;
  hardStopPolicy?: Record<string, unknown>;
  priorityDemotePolicy?: Record<string, unknown>;
  singleSourcePolicy?: Record<string, unknown>;
  cacheAffinityPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status: 'active' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export interface GatewayRunnerPolicyUpsertRequest {
  policyKey?: string;
  name?: string;
  description?: string;
  failoverPolicy?: RunnerFailoverPolicy;
  hardStopPolicy?: Record<string, unknown>;
  priorityDemotePolicy?: Record<string, unknown>;
  singleSourcePolicy?: Record<string, unknown>;
  cacheAffinityPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | string;
}

export interface GatewaySkillBundleMetadata {
  name: string;
  version: string;
  displayName: string;
  modules: string[];
  fileName: string;
  downloadPath: string;
  apiDocsJsonPath: string;
  apiDocsYamlPath: string;
}

export interface GatewayUser {
  id: string;
  userKey: string;
  source: 'gateway' | 'server-main' | 'sync' | string;
  externalUserId?: string;
  username: string;
  displayName?: string;
  email?: string;
  phone?: string;
  avatarUrl?: string;
  gatewayTenantId?: string;
  tenantId?: string;
  tenantKey?: string;
  defaultUserGroupId?: string;
  roles?: string[];
  authProfile?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  walletAccounts?: GatewayWalletAccount[];
  status: 'active' | 'disabled' | 'locked' | 'deleted' | string;
  lastLoginAt?: string;
  syncedAt?: string;
  sourceUpdatedAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface GatewayUserUpsertRequest {
  userKey?: string;
  source?: 'gateway' | 'server-main' | 'sync' | string;
  externalUserId?: string;
  username: string;
  displayName?: string;
  email?: string;
  phone?: string;
  avatarUrl?: string;
  password?: string;
  gatewayTenantId?: string;
  tenantId?: string;
  tenantKey?: string;
  defaultUserGroupId?: string;
  roles?: string[];
  authProfile?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | 'locked' | 'deleted' | string;
}

export interface GatewayTenant {
  id: string;
  tenantKey: string;
  source: 'gateway' | 'server-main' | 'sync' | string;
  externalTenantId?: string;
  name: string;
  description?: string;
  defaultUserGroupId?: string;
  planKey?: string;
  billingProfile?: Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  authPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status: 'active' | 'disabled' | 'locked' | 'deleted' | string;
  syncedAt?: string;
  sourceUpdatedAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface GatewayTenantUpsertRequest {
  tenantKey: string;
  source?: 'gateway' | 'server-main' | 'sync' | string;
  externalTenantId?: string;
  name: string;
  description?: string;
  defaultUserGroupId?: string;
  planKey?: string;
  billingProfile?: Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  authPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | 'locked' | 'deleted' | string;
}

export interface UserGroup {
  id: string;
  groupKey: string;
  name: string;
  description?: string;
  source: 'gateway' | 'server-main' | 'sync' | string;
  priority: number;
  rechargeDiscountPolicy?: Record<string, unknown>;
  billingDiscountPolicy?: Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  quotaPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status: 'active' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export interface UserGroupUpsertRequest {
  groupKey: string;
  name: string;
  description?: string;
  source?: 'gateway' | 'server-main' | 'sync' | string;
  priority?: number;
  rechargeDiscountPolicy?: Record<string, unknown>;
  billingDiscountPolicy?: Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  quotaPolicy?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | string;
}

export interface UserGroupMembership {
  id: string;
  groupId: string;
  principalType: 'user' | 'tenant' | 'api_key' | 'organization' | string;
  principalId: string;
  source: 'gateway' | 'server-main' | 'sync' | string;
  priority: number;
  effectiveFrom?: string;
  effectiveTo?: string;
  status: 'active' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export type GatewayAccessSubjectType = 'user_group' | 'tenant' | 'user' | 'api_key';
export type GatewayAccessResourceType = 'platform' | 'platform_model' | 'base_model';
export type GatewayAccessEffect = 'allow' | 'deny';

export interface GatewayAccessRule {
  id: string;
  subjectType: GatewayAccessSubjectType | string;
  subjectId: string;
  resourceType: GatewayAccessResourceType | string;
  resourceId: string;
  effect: GatewayAccessEffect | string;
  priority: number;
  minPermissionLevel: number;
  conditions?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status: 'active' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export interface GatewayAccessRuleUpsertRequest {
  subjectType: GatewayAccessSubjectType | string;
  subjectId: string;
  resourceType: GatewayAccessResourceType | string;
  resourceId: string;
  effect: GatewayAccessEffect | string;
  priority?: number;
  minPermissionLevel?: number;
  conditions?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | string;
}

export interface GatewayAccessRuleResourceRequest {
  resourceType: GatewayAccessResourceType | string;
  resourceId: string;
  priority?: number;
  minPermissionLevel?: number;
  conditions?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  status?: 'active' | 'disabled' | string;
}

export interface GatewayAccessRuleBatchRequest {
  subjectType: GatewayAccessSubjectType | string;
  subjectId: string;
  effect: GatewayAccessEffect | string;
  upsertResources?: GatewayAccessRuleResourceRequest[];
  deleteResources?: GatewayAccessRuleResourceRequest[];
}

export interface GatewayApiKey {
  id: string;
  gatewayTenantId?: string;
  gatewayUserId: string;
  tenantId?: string;
  tenantKey?: string;
  userId?: string;
  keyPrefix: string;
  secret?: string;
  name: string;
  scopes?: string[];
  userGroupId?: string;
  rateLimitPolicy?: RateLimitPolicy;
  quotaPolicy?: Record<string, unknown>;
  status: 'active' | 'disabled' | 'revoked' | string;
  expiresAt?: string;
  lastUsedAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface CreatedGatewayApiKey {
  apiKey: GatewayApiKey;
  secret: string;
}

export interface GatewayApiKeyScopeUpdateRequest {
  scopes: string[];
}

export interface PlayableGatewayApiKey extends GatewayApiKey {
  secret: string;
}

export interface GatewayPricingEstimateItem {
  amount?: number;
  currency?: string;
  discountFactor?: number;
  durationSeconds?: number;
  durationUnit?: string;
  durationUnitCount?: number;
  model?: string;
  modelAlias?: string;
  platformId?: string;
  platformModelId?: string;
  provider?: string;
  quantity?: number | string;
  resourceType?: string;
  simulated?: boolean;
  unit?: string;
  [key: string]: unknown;
}

export interface GatewayPricingEstimate {
  items: GatewayPricingEstimateItem[];
  resolver: string;
  totalAmount?: number;
  reservationAmount?: number;
  currency?: string;
  candidateCount: number;
  pricingVersion: string;
  requestFingerprint: string;
}

export interface GatewayWalletAccount {
  id: string;
  gatewayTenantId?: string;
  gatewayUserId: string;
  tenantId?: string;
  tenantKey?: string;
  userId?: string;
  currency: 'resource' | 'credit' | 'cny' | 'usd' | string;
  balance: number;
  frozenBalance: number;
  totalRecharged: number;
  totalSpent: number;
  status: 'active' | 'frozen' | 'disabled' | string;
  createdAt: string;
  updatedAt: string;
}

export interface GatewayWalletTransaction {
  id: string;
  accountId: string;
  currency?: 'resource' | 'credit' | 'cny' | 'usd' | string;
  gatewayTenantId?: string;
  gatewayUserId?: string;
  direction: 'credit' | 'debit' | 'freeze' | 'unfreeze' | string;
  transactionType: 'recharge' | 'grant' | 'admin_adjust' | 'task_billing' | 'refund' | 'reserve' | 'release' | string;
  amount: number;
  balanceBefore: number;
  balanceAfter: number;
  idempotencyKey?: string;
  referenceType?: string;
  referenceId?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
}

export interface WalletBalanceAdjustmentRequest {
  currency?: string;
  balance: number;
  reason: string;
  idempotencyKey?: string;
  metadata?: Record<string, unknown>;
}

export interface WalletRechargeRequest {
  currency?: string;
  amount: number;
  reason: string;
  idempotencyKey?: string;
  metadata?: Record<string, unknown>;
}

export interface WalletSummaryResponse {
  accounts: GatewayWalletAccount[];
  primaryAccount: GatewayWalletAccount;
}

export interface GatewayDesktopConfigResponse {
  billing: {
    gatewayBaseUrl?: string;
    gatewayBillingPath: string;
  };
}

export interface WalletAdjustmentResponse {
  account: GatewayWalletAccount;
  before: GatewayWalletAccount;
  transaction: GatewayWalletTransaction;
  auditLog: GatewayAuditLog;
}

export interface GatewayAuditLog {
  id: string;
  category: string;
  action: string;
  actorGatewayUserId?: string;
  actorUserId?: string;
  actorUsername?: string;
  actorSource?: string;
  actorRoles?: string[];
  targetType: string;
  targetId: string;
  targetGatewayUserId?: string;
  targetGatewayTenantId?: string;
  requestIp?: string;
  userAgent?: string;
  beforeState?: Record<string, unknown>;
  afterState?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  createdAt: string;
}

export interface GatewayRechargeOrder {
  id: string;
  gatewayTenantId?: string;
  gatewayUserId: string;
  tenantId?: string;
  tenantKey?: string;
  userId?: string;
  amount: number;
  bonusAmount: number;
  payableAmount: number;
  currency: 'resource' | 'credit' | 'cny' | 'usd' | string;
  channel: 'manual' | 'wechat' | 'alipay' | 'stripe' | 'paypal' | string;
  status: 'created' | 'pending' | 'paid' | 'closed' | 'failed' | string;
  externalOrderId?: string;
  idempotencyKey?: string;
  paidAt?: string;
  metadata?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

export interface RateLimitRule {
  metric: RateLimitMetric;
  limit: number;
  windowSeconds?: number;
  leaseTtlSeconds?: number;
  maxWaitSeconds?: number;
  consume?: 'fixed_window' | 'reserve_then_reconcile' | string;
}

export interface RateLimitPolicy {
  rules?: RateLimitRule[];
  [key: string]: unknown;
}

export interface BillingConfig {
  resourceType?: string;
  basePrice?: number;
  baseWeight?: Record<string, unknown>;
  dynamicWeight?: Record<string, unknown>;
  [key: string]: unknown;
}

export interface PlatformModel {
  id: string;
  platformId: string;
  baseModelId?: string;
  provider?: string;
  platformName?: string;
  modelName: string;
  providerModelName?: string;
  /** @deprecated Use modelName. */
  modelAlias?: string;
  legacyAliases?: string[];
  modelType: string[];
  displayName: string;
  capabilityOverride?: Record<string, unknown>;
  capabilities?: Record<string, unknown>;
  pricingMode: PricingMode;
  discountFactor?: number;
  pricingRuleSetId?: string;
  billingConfigOverride?: BillingConfig;
  billingConfig?: BillingConfig;
  permissionConfig?: Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  rateLimitPolicy?: RateLimitPolicy;
  rateLimitPolicyMode: 'inherit' | 'override';
  runtimePolicySetId?: string;
  runtimePolicyOverride?: RuntimePolicyOverride;
  cooldownUntil?: string;
  enabled: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface ModelCatalogFilterOption {
  value: string;
  label: string;
  count: number;
  iconPath?: string;
}

export interface ModelCatalogProviderSummary {
  key: string;
  name: string;
  iconPath?: string;
  sourceCount: number;
}

export interface ModelCatalogText {
  label: string;
  title?: string;
}

export interface ModelCatalogPricing {
  lines: string[];
  title?: string;
}

export interface ModelCatalogRateLimits {
  rpm?: number;
  tpm?: number;
  concurrent?: number;
  label: string;
  title?: string;
}

export interface ModelCatalogPermission {
  label: string;
  title?: string;
  allowGroups?: string[];
  denyGroups?: string[];
}

export interface ModelCatalogSource {
  id: string;
  platformId?: string;
  platformName?: string;
  providerKey: string;
  providerName: string;
  modelName: string;
  providerModelName?: string;
  modelAlias?: string;
  legacyAliases?: string[];
  displayName: string;
  modelType: string[];
  enabled: boolean;
  rateLimits: ModelCatalogRateLimits;
}

export type SupportedTextApiProtocol =
  | 'openai_chat_completions'
  | 'openai_responses'
  | 'anthropic_messages';

export interface TextGenerateCapability {
  supportedApiProtocols?: SupportedTextApiProtocol[];
  [key: string]: unknown;
}

export interface ModelCatalogItem {
  id: string;
  alias: string;
  displayName: string;
  modelName: string;
  description?: string;
  iconPath?: string;
  modelType: string[];
  capabilityTags: string[];
  providerKeys: string[];
  providers: ModelCatalogProviderSummary[];
  sourceCount: number;
  source: ModelCatalogText;
  discount: ModelCatalogText;
  rateLimits: ModelCatalogRateLimits;
  permission: ModelCatalogPermission;
  pricing: ModelCatalogPricing;
  enabled: boolean;
  statusLabel?: string;
  sources?: ModelCatalogSource[];
}

export interface ModelCatalogResponse {
  items: ModelCatalogItem[];
  filters: {
    capabilities: ModelCatalogFilterOption[];
    providers: ModelCatalogFilterOption[];
  };
  summary: {
    modelCount: number;
    sourceCount: number;
  };
}

export interface RateLimitWindow {
  scopeType: string;
  scopeKey: string;
  metric: RateLimitMetric | string;
  windowStart: string;
  limitValue: number;
  usedValue: number;
  reservedValue: number;
  resetAt: string;
  updatedAt: string;
}

export interface RateLimitMetricStatus {
  currentValue: number;
  usedValue: number;
  reservedValue: number;
  limitValue: number;
  limited: boolean;
  ratio: number;
  resetAt?: string;
}

export interface PriorityDemotionRecord {
  id: string;
  taskId: string;
  platformId: string;
  platformModelId?: string;
  reason?: string;
  errorCode?: string;
  errorMessage?: string;
  category?: string;
  statusCode?: number;
  policySource?: string;
  policy?: string;
  policyRule?: string;
  matchedValue?: string;
  dynamicPriority?: number;
  createdAt: string;
}

export interface PlatformPolicyEvent {
  id: string;
  taskId: string;
  platformId: string;
  platformModelId?: string;
  eventType: string;
  reason?: string;
  errorCode?: string;
  errorMessage?: string;
  category?: string;
  statusCode?: number;
  policySource?: string;
  policy?: string;
  policyRule?: string;
  matchedValue?: string;
  createdAt: string;
}

export interface PlatformDynamicPriorityUpdateRequest {
  dynamicPriority?: number;
  reset?: boolean;
}

export interface PlatformDynamicPriorityState {
  platformId: string;
  priority: number;
  dynamicPriority?: number;
  effectivePriority: number;
  updatedAt: string;
}

export interface ModelRateLimitStatus {
  platformModelId: string;
  platformId: string;
  platformName: string;
  provider: string;
  platformStatus?: string;
  platformDisabledReason?: PlatformPolicyEvent;
  platformPriority: number;
  platformDynamicPriority?: number;
  platformEffectivePriority: number;
  modelName: string;
  providerModelName?: string;
  modelAlias?: string;
  displayName: string;
  modelType: string[];
  enabled: boolean;
  rateLimitPolicy?: RateLimitPolicy | Record<string, unknown>;
  platformCooldownUntil?: string;
  modelCooldownUntil?: string;
  concurrent: RateLimitMetricStatus;
  queuedTasks: number;
  waitingSyncTasks?: number;
  waitingAsyncTasks?: number;
  oldestQueueWaitSeconds?: number;
  queueLimit?: number;
  rpm: RateLimitMetricStatus;
  tpm: RateLimitMetricStatus;
  loadRatio: number;
  recentPriorityDemotions?: PriorityDemotionRecord[];
}

export interface GatewayNetworkProxyConfig {
  globalHttpProxy?: string;
  globalHttpProxySet: boolean;
  globalHttpProxySource?: string;
}

export interface FileStorageChannel {
  id: string;
  channelKey: string;
  name: string;
  provider: 'server_main_openapi' | 'aliyun_oss' | 'tencent_cos' | string;
  uploadUrl?: string;
  credentialsPreview?: Record<string, unknown>;
  scenes?: string[];
  config?: Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  priority: number;
  status: 'enabled' | 'disabled' | string;
  lastError?: string;
  lastFailedAt?: string;
  lastSucceededAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface FileStorageChannelUpsertRequest {
  channelKey: string;
  name: string;
  provider?: 'server_main_openapi' | 'aliyun_oss' | 'tencent_cos' | string;
  uploadUrl?: string;
  apiKey?: string;
  scenes?: string[];
  config?: Record<string, unknown>;
  retryPolicy?: Record<string, unknown>;
  priority?: number;
  status?: 'enabled' | 'disabled' | string;
}

export interface FileStorageSettings {
  resultUploadPolicy: 'default' | 'upload_all' | 'upload_none' | string;
}

export interface FileStorageSettingsUpdateRequest {
  resultUploadPolicy: 'default' | 'upload_all' | 'upload_none' | string;
}

export interface ClientCustomizationSettings {
  clientName: string;
  clientEnglishName: string;
  platformName: string;
  iconPath: string;
}

export interface ClientCustomizationSettingsUpdateRequest {
  clientName?: string;
  clientEnglishName?: string;
  platformName?: string;
  iconPath?: string;
}

export interface SecurityEventConnection {
  connectionId: string;
  transmitterIssuer: string;
  receiverEndpoint: string;
  audience?: string;
  streamId?: string;
  lifecycleStatus: 'connecting' | 'verifying' | 'bootstrap' | 'enabled' | 'degraded' | 'rotating' | 'disconnect_pending' | 'retiring' | 'error' | string;
  healthMode: 'disabled' | 'bootstrap' | 'push_healthy' | 'introspection_fallback' | string;
  managementClientId: string;
  lastVerificationAt?: string;
  lastErrorCategory?: string;
  version: number;
}

export interface SecurityEventConnectionPrerequisites {
  oidcConfigured: boolean;
  introspectionClientConfigured: boolean;
  publicBaseUrlConfigured: boolean;
  managementClientId: string;
  credentialInputSupported: boolean;
}

export interface SecurityEventConnectionResponse {
  connected: boolean;
  traceId?: string;
  auditId?: string;
  lifecycleStatus?: 'disconnected' | string;
  connection?: SecurityEventConnection;
  prerequisites?: SecurityEventConnectionPrerequisites;
}

export type IdentityRevisionState = 'draft' | 'validated' | 'active' | 'superseded' | 'failed';

export interface IdentityConfigurationRevision {
  id: string;
  state: IdentityRevisionState;
  schemaVersion: number;
  tenantMode: 'single_tenant' | 'multi_tenant';
  authCenterUrl: string;
  issuer?: string;
  tenantId?: string;
  applicationId?: string;
  audience?: string;
  browserClientId?: string;
  machineClientId?: string;
  scopes: string[];
  capabilities: string[];
  rolePrefix: string;
  localTenantKey: string;
  publicBaseUrl: string;
  webBaseUrl: string;
  jitEnabled: boolean;
  legacyJwtEnabled: boolean;
  tokenIntrospection: boolean;
  sessionRevocation: boolean;
  securityEventIssuer?: string;
  securityEventConfigurationUrl?: string;
  securityEventAudience?: string;
  sessionIdleSeconds: number;
  sessionAbsoluteSeconds: number;
  sessionRefreshSeconds: number;
  version: number;
  lastErrorCategory?: string;
  lastTraceId?: string;
  lastAuditId?: string;
  validatedAt?: string;
  activatedAt?: string;
  supersededAt?: string;
  createdAt: string;
  updatedAt: string;
}

export type IdentityPairingStatus =
  | 'metadata_pending'
  | 'preparing'
  | 'ready'
  | 'credentials_saved'
  | 'completed'
  | 'failed'
  | 'expired'
  | 'cancelled';

export type IdentityPairingCleanupStatus = 'none' | 'pending' | 'completed';

export interface IdentityPairingExchange {
  id: string;
  revisionId: string;
  remoteExchangeId: string;
  status: IdentityPairingStatus;
  cleanupStatus: IdentityPairingCleanupStatus;
  remoteVersion: number;
  expiresAt: string;
  version: number;
  lastErrorCategory?: string;
  authCenterAuditId?: string;
  lastTraceId?: string;
  cancelledAt?: string;
  cleanupCompletedAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface IdentityRuntimeStatus {
  enabled: boolean;
  revisionId?: string;
  login: string;
  jit: string;
  tokenIntrospection: string;
  sessionRevocation: string;
  lastTraceId?: string;
  lastAuditId?: string;
  lastErrorCategory?: string;
}

export interface IdentityConfigurationView {
  active: IdentityConfigurationRevision | null;
  draft: IdentityConfigurationRevision | null;
  previous: IdentityConfigurationRevision | null;
  pairing?: IdentityPairingExchange;
  runtime: IdentityRuntimeStatus;
}

export interface PublicIdentityConfiguration {
  enabled: boolean;
  oidcLogin: boolean;
  loginUrl?: string;
  logoutUrl?: string;
  status: string;
}

export interface IdentityPairingInput {
  authCenterUrl: string;
  onboardingCode: string;
  publicBaseUrl: string;
  webBaseUrl: string;
  localTenantKey: string;
  legacyJwtEnabled: boolean;
}

export interface IdentityRevisionPolicyUpdate {
  localTenantKey?: string;
  rolePrefix?: string;
  jitEnabled?: boolean;
  legacyJwtEnabled?: boolean;
  sessionIdleSeconds?: number;
  sessionAbsoluteSeconds?: number;
  sessionRefreshSeconds?: number;
}

export interface GatewayTask {
  id: string;
  kind: string;
  runMode?: 'production' | 'simulation' | string;
  userId: string;
  gatewayUserId?: string;
  userSource?: 'gateway' | 'server-main' | 'sync' | string;
  gatewayTenantId?: string;
  tenantId?: string;
  tenantKey?: string;
  apiKeyId?: string;
  apiKeyName?: string;
  apiKeyPrefix?: string;
  userGroupId?: string;
  userGroupKey?: string;
  userGroupPolicySnapshot?: Record<string, unknown>;
  model: string;
  modelType?: string;
  requestedModel?: string;
  resolvedModel?: string;
  requestId?: string;
  request?: Record<string, unknown>;
  asyncMode?: boolean;
  status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | string;
  result?: Record<string, unknown>;
  billings?: unknown[];
  usage?: Record<string, unknown>;
  metrics?: Record<string, unknown>;
  billingSummary?: Record<string, unknown>;
  finalChargeAmount?: number;
  billingVersion?: string;
  billingStatus?: 'not_started' | 'pending' | 'processing' | 'settled' | 'released' | 'retryable_failed' | 'manual_review' | 'not_required' | string;
  billingCurrency?: string;
  pricingSnapshot?: Record<string, unknown>;
  requestFingerprint?: string;
  reservationAmount?: number;
  executionLeaseExpiresAt?: string;
  billingUpdatedAt?: string;
  billingSettledAt?: string;
  responseStartedAt?: string;
  responseFinishedAt?: string;
  responseDurationMs?: number;
  finishedAt?: string;
  error?: string;
  errorCode?: string;
  errorMessage?: string;
  attempts?: GatewayTaskAttempt[];
  createdAt: string;
  updatedAt: string;
}

export interface AdminTaskUserSummary {
  id: string;
  username?: string;
  displayName?: string;
  email?: string;
  source?: string;
}

export interface AdminTaskTenantSummary {
  id: string;
  tenantKey?: string;
  name?: string;
}

export interface AdminTaskPlatformSummary {
  id: string;
  name?: string;
  provider?: string;
}

export interface AdminGatewayTask extends GatewayTask {
  adminContext: {
    user?: AdminTaskUserSummary;
    tenant?: AdminTaskTenantSummary;
    latestPlatform?: AdminTaskPlatformSummary;
  };
}

export interface GatewayTaskParamPreprocessingLog {
  id: string;
  taskId: string;
  attemptId?: string;
  attemptNo?: number;
  modelType?: string;
  platformId?: string;
  platformModelId?: string;
  clientId?: string;
  changed: boolean;
  changeCount: number;
  actualInput?: Record<string, unknown>;
  convertedOutput?: Record<string, unknown>;
  changes?: Array<Record<string, unknown>>;
  model?: Record<string, unknown>;
  createdAt: string;
}

export interface GatewayTaskAttempt {
  id: string;
  taskId: string;
  attemptNo: number;
  platformId?: string;
  platformName?: string;
  provider?: string;
  platformModelId?: string;
  modelName?: string;
  providerModelName?: string;
  modelAlias?: string;
  modelType?: string;
  clientId?: string;
  queueKey: string;
  status: 'running' | 'succeeded' | 'failed' | string;
  retryable: boolean;
  simulated: boolean;
  requestId?: string;
  statusCode?: number;
  usage?: Record<string, unknown>;
  metrics?: Record<string, unknown>;
  requestSnapshot?: Record<string, unknown>;
  responseSnapshot?: Record<string, unknown>;
  responseStartedAt?: string;
  responseFinishedAt?: string;
  responseDurationMs?: number;
  pricingSnapshot?: Record<string, unknown>;
  requestFingerprint?: string;
  upstreamSubmissionStatus?: 'not_submitted' | 'submitting' | 'response_received' | string;
  upstreamSubmissionUpdatedAt?: string;
  errorCode?: string;
  errorMessage?: string;
  startedAt: string;
  finishedAt?: string;
}

export interface BillingSettlement {
  id: string;
  taskId: string;
  action: 'settle' | 'release' | string;
  amount: number;
  currency: string;
  status: 'pending' | 'processing' | 'retryable_failed' | 'completed' | 'manual_review' | string;
  attempts: number;
  nextAttemptAt: string;
  lockedBy?: string;
  lockedAt?: string;
  lastErrorCode?: string;
  lastErrorMessage?: string;
  manualReviewReason?: string;
  pricingSnapshot?: Record<string, unknown>;
  payload?: Record<string, unknown>;
  completedAt?: string;
  createdAt: string;
  updatedAt: string;
}

export interface BillingSettlementListResponse {
  items: BillingSettlement[];
  total: number;
  page: number;
  pageSize: number;
}

export interface BillingSettlementRetryResponse {
  settlement: BillingSettlement;
  auditLog?: GatewayAuditLog;
}

export interface GatewayTaskEvent {
  id: string;
  taskId: string;
  seq: number;
  eventType: string;
  status?: string;
  phase?: string;
  progress?: number;
  message?: string;
  payload?: Record<string, unknown>;
  simulated: boolean;
  createdAt: string;
}

export interface ListResponse<T> {
  items: T[];
  page?: number;
  pageSize?: number;
  total?: number;
}
