export {};

declare global {
  interface HTMLElement {
    value?: any;
    checked?: boolean;
    disabled?: boolean;
    placeholder?: string;
    src?: string;
    naturalWidth?: number;
    naturalHeight?: number;
    complete?: boolean;
    executeJavaScript?(script: string): Promise<unknown>;
    reload?(): void;
  }

  interface Element {
    offsetHeight?: number;
    src?: string;
    value?: any;
    executeJavaScript?(script: string): Promise<unknown>;
  }

  interface EventTarget {
    value?: any;
    files?: FileList | null;
    checked?: boolean;
    disabled?: boolean;
    classList?: DOMTokenList;
  }

  interface Event {
    detail?: any;
    url?: unknown;
    code?: unknown;
    message?: unknown;
    reason?: unknown;
    oldUrl?: unknown;
    newUrl?: unknown;
    errorCode?: unknown;
    errorDescription?: unknown;
    validatedURL?: unknown;
  }

  interface Error {
    type?: string;
  }

  interface Navigator {
    userLanguage?: string;
  }

  interface Performance {
    memory?: {
      usedJSHeapSize: number;
      totalJSHeapSize: number;
      jsHeapSizeLimit: number;
    };
  }

  interface DebugManagerLike {
    config?: {
      debugEnabled?: boolean;
    };
    originalConsole?: {
      log: (...args: unknown[]) => void;
      info: (...args: unknown[]) => void;
      warn: (...args: unknown[]) => void;
      error: (...args: unknown[]) => void;
      debug?: (...args: unknown[]) => void;
      trace?: (...args: unknown[]) => void;
      group?: (...args: unknown[]) => void;
      groupCollapsed?: (...args: unknown[]) => void;
      groupEnd?: (...args: unknown[]) => void;
      table?: (...args: unknown[]) => void;
    };
    log(...args: unknown[]): void;
    logError(...args: unknown[]): void;
    logDev?(...args: unknown[]): void;
    logImageProcessing?(...args: unknown[]): void;
    logSelectionInfo?(...args: unknown[]): void;
    logApiCall?(...args: unknown[]): void;
    logNetwork?(...args: unknown[]): void;
    logPluginUpdate?(...args: unknown[]): void;
    logPluginUpdateError?(...args: unknown[]): void;
    logUxEvent?(...args: unknown[]): void;
  }

  interface RegionConfig {
    region: "default";
    baseUrl: string;
    domainUrl?: string;
    confidence?: string;
    timezone?: string;
    language?: string;
    testedLatency?: number;
  }

  interface PluginAvailabilityState {
    checked: boolean;
    isBlocked: boolean;
    message: string;
  }

  interface WukongDiagnosticsLike {
    runStartupCheck(): Record<string, any>;
    collectSnapshot(): Record<string, any>;
    exportJsonText(): string;
    downloadJson(): void;
    getRecentErrors(): unknown[];
    getLastStartupReport(): Record<string, any> | null;
  }

  interface AuthUser {
    id?: number | string;
    username?: string;
    role?: string;
    balance?: number | string;
    [key: string]: unknown;
  }

  interface RegionDetectorLike {
    getRegionConfig(): RegionConfig;
    detectWithNetworkTest?(): Promise<RegionConfig>;
    getBaseUrl(): string;
    getDomainUrl?(): string;
    getTenantId?(): string;
    getSoftwareCode?(): string;
    getDeviceId?(): string;
    buildApiUrl?(path?: string): string;
    buildAssetUrl?(path?: string): string;
    getJsonHeaders?(extra?: Record<string, string>): Record<string, string>;
    getAuthHeaders?(token?: string, extra?: Record<string, string>): Record<string, string>;
    logRegionInfo?(): RegionConfig;
  }

  interface PluginGateManagerLike {
    init(): Promise<PluginAvailabilityState>;
    ensureReady?(): Promise<PluginAvailabilityState>;
    isBlocked(): boolean;
  }

  interface AuthLoginResult {
    success: boolean;
    user?: AuthUser;
    message?: string;
  }

  interface AuthRegisterResult {
    success: boolean;
    message?: string;
  }

  interface AuthServiceLike {
    isLoggedIn(): boolean;
    isPluginMode?(): boolean;
    getUser(): AuthUser | null;
    getToken(): string | null;
    getSoftwareCode?(): string;
    getPluginContext?(): {
      entitlements: unknown[];
      softwares: unknown[];
    };
    getCurrentUser?(): Promise<unknown>;
    listEntitlements?(): Promise<unknown[]>;
    listSoftwares?(): Promise<unknown[]>;
    refreshPluginContext?(): Promise<unknown>;
    listAnnouncements?(options?: {
      unread?: boolean;
      softwareCode?: string;
    }): Promise<unknown[]>;
    markAnnouncementRead?(id: number | string): Promise<boolean>;
    refreshBalance?(): Promise<unknown> | unknown;
    login(username: string, password: string): Promise<AuthLoginResult>;
    register(
      username: string,
      password: string,
      invitationCode?: string
    ): Promise<AuthRegisterResult>;
    logoutRemote?(): Promise<unknown>;
    logout(): void;
  }

  interface I18nLike {
    locale?: string;
    translations?: Record<string, string>;
    init?(): Promise<void>;
    t(key: string, params?: Record<string, string | number>): string;
    setLocale?(locale: string): Promise<boolean>;
    getLocale?(): string;
  }

  interface MainAppLike {
    startSelectionMonitor?(): void;
    stopSelectionMonitor?(): void;
    updateUITexts?(): void;
    closeApiConfigPanel?(): void;
    handleTokenExpired?(): void;
    getButton?(id: string): HTMLButtonElement | null;
    getDiv?(id: string): HTMLElement | null;
    getInput?(id: string): HTMLInputElement | null;
    getSelect?(id: string): HTMLSelectElement | null;
    getCheckbox?(id: string): HTMLInputElement | null;
    isCancelled?: boolean;
    useBalanceMode?: boolean;
  }

  type WukongImageLike =
    | string
    | {
        data?: string;
        width?: number;
        height?: number;
      }
    | null;

  interface RHAppLike {
    init?(): void;
    renderDynamicInputs?(): void;
    renderOutputs?(): void;
    renderTaskList?(): void;
  }

  interface KeyValidationResult {
    valid: boolean;
    message: string;
  }

  interface KeyValidatorLike {
    validateKey(apiKey: string, force?: boolean): Promise<KeyValidationResult>;
    validateKeyAsync(
      apiKey: string,
      callback: (valid: boolean, message: string) => void,
      force?: boolean
    ): void;
    clearCache?(): void;
    isValid?(): boolean;
    reset?(): void;
    startAutoValidation?(apiKey: string): void;
    stopAutoValidation?(): void;
  }

  interface AnnouncementManagerLike {
    init(): void;
    loadAnnouncement?(): Promise<void>;
    showAnnouncement?(text: string): void;
    hideAnnouncement?(): void;
  }

  interface PluginUpdateManagerLike {
    setupEventListeners(): void;
    updateUITexts(): void;
  }

  interface WukongStorageLike {
    getString(key: string, fallbackValue?: string): string;
    getFirstString(keys: string[] | string, fallbackValue?: string): string;
    setString(key: string, value: string): boolean;
    remove(key: string): boolean;
    getBool(key: string, fallbackValue?: boolean): boolean;
    setBool(key: string, value: boolean): boolean;
    getJSON(key: string, fallbackValue?: any): any;
    getFirstJSON(keys: string[] | string, fallbackValue?: any): any;
    setJSON(key: string, value: unknown): boolean;
  }

  interface SDAPILike {
    [key: string]: any;
  }

  interface GeminiAPILike {
    [key: string]: any;
  }

  interface EcommercePanelLike {
    [key: string]: any;
  }

  interface LocaleManagerLike {
    getText(key: string): string;
    onLocaleChange?(callback: (locale: string) => void): void;
    formatErrorMessage?(error: unknown): string;
    setLocale?(locale: string): void;
    [key: string]: any;
  }

  interface WKApiManagerLike {
    isConnected?: boolean;
    serverClosed?: boolean;
    isReconnecting?: boolean;
    socket?: {
      connected?: boolean;
      [key: string]: any;
    };
    on?(eventName: string, listener: (...args: any[]) => void): void;
    sendMessage?(eventName: string, payload?: unknown): unknown;
    connect?(url?: string): Promise<boolean> | boolean;
    disconnect?(force?: boolean): Promise<void> | void;
    [key: string]: any;
  }

  interface WKConnectionManagerLike {
    connect?(): Promise<boolean> | boolean;
    disconnect?(): Promise<void> | void;
    [key: string]: any;
  }

  interface WKLicenseManagerLike {
    [key: string]: any;
  }

  interface WKGenerationControllerLike {
    [key: string]: any;
  }

  interface WKWorkflowLoaderLike {
    [key: string]: any;
  }

  interface WKComfyControllerLike {
    [key: string]: any;
  }

  interface ImageOperationsI18nLike {
    getText(key: string): string;
    [key: string]: any;
  }

  interface ScriptBaseLike {
    photoshop?: any;
    app?: any;
    action?: any;
    core?: any;
    imaging?: any;
    batchPlay?: any;
    dialogs?: any;
    storage?: any;
    safeAlert?: (title: string, message: string) => Promise<void>;
    getLocalizedMessage?: (key: string, fallback: string) => string;
    isReady?: boolean;
  }

  interface PsapiBridgeLike {
    socket?: {
      connected?: boolean;
      emit?: (...args: any[]) => unknown;
      [key: string]: any;
    };
    [key: string]: any;
  }

  interface ImageOperationsLike {
    reinitializePanel?(): void;
    [key: string]: any;
  }

  interface WKWorkflowListManagerLike {
    [key: string]: any;
  }

  interface WKSettingsManagerLike {
    [key: string]: any;
  }

  interface WKUIControllerLike {
    settings?: Record<string, any>;
    loadWorkflows?(): Promise<unknown>;
    [key: string]: any;
  }

  interface WKInstancesLike {
    workflowLoader?: WKWorkflowLoaderLike | null;
    uiController?: WKUIControllerLike | null;
    initialized?: boolean;
  }

  interface WidgetFactoryLike {
    createWidget(config: any): any;
    [key: string]: any;
  }

  interface SeedManagerLike {
    autoRandomStates?: Record<string, boolean>;
    setAutoRandom?(nodeId: string, widgetName: string, state: boolean): boolean;
    getAutoRandom?(nodeId: string, widgetName: string): boolean;
    [key: string]: any;
  }

  interface ImagePreviewManagerLike {
    clearAll?(): void;
    onWorkflowChange?(): void;
    onFreeModeEnter?(): void;
    [key: string]: any;
  }

  interface PSWebUILike {
    isDisabled?(): boolean;
    [key: string]: any;
  }

  interface PSAPIStatusLike {
    connected?: boolean;
    lastUpdate?: number;
    pageId?: string;
    isLeader?: boolean;
    isWSConnected?(): boolean;
    [key: string]: any;
  }

  interface PSOperationsModuleLike {
    applyRenderedImage?(...args: any[]): Promise<unknown> | unknown;
    [key: string]: any;
  }

  interface UtilsModuleLike {
    showMessage?(...args: any[]): void;
    [key: string]: any;
  }

  interface PageCoordinatorLike {
    pageId?: string;
    isLeader?: boolean;
    requestLeadership?(): void;
    cleanup?(): void;
    broadcastToOtherPages?(key: string, data: unknown): void;
    [key: string]: any;
  }

  interface QRCodeLike {
    CorrectLevel: {
      H: unknown;
    };
    new (container: Element | string, options?: Record<string, unknown>): unknown;
  }

  interface PresetManagerLike {
    init(): Promise<void>;
    handlePresetChange?(presetValue: string): void;
    reloadPresets?(): Promise<void>;
    verifySelectorState?(): void;
    forceLoadPresets?(): Promise<void>;
    forceUpdateSelector?(): void;
    testPresetSelection?(): void;
    forceShowSelector?(): void;
    recreateSelector?(): void;
    createButtonSelector?(): void;
  }

  interface PSDocumentInfo {
    width: number;
    height: number;
    name: string;
    id?: number | string;
  }

  interface PSSelectionBounds {
    left: number;
    top: number;
    right: number;
    bottom: number;
    width: number;
    height: number;
  }

  interface PSSelectionInfo {
    hasSelection: boolean;
    bounds: PSSelectionBounds | null;
    channelName?: string | null;
    selection_boundary?: PSSelectionBounds;
    selectionBoundary?: PSSelectionBounds;
    document_boundary?: PSSelectionBounds;
    documentBoundary?: PSSelectionBounds;
  }

  interface PSExportSelectionResult {
    success?: boolean;
    imageData?: string;
    base64?: string;
    channelName?: string | null;
    captureContext?: unknown;
    selection_boundary?: PSSelectionBounds;
    document_boundary?: PSSelectionBounds;
    bounds?: PSSelectionBounds | null;
    hasSelection?: boolean;
    [key: string]: unknown;
  }

  interface ImageHandlerLike {
    currentSlot: number;
    uploadedImages: WukongImageLike[];
    comfyImage?: string | null;
    comfyMask?: string | null;
    selectionPreviewData?: string | null;
    limitUploadSize?: boolean;
    maxUploadSize?: number;
    uploadFullCanvas(): Promise<void>;
    uploadLayerCanvas(): Promise<void>;
    uploadQuickLayer(): Promise<void>;
    getFullDocumentBase64?(): Promise<any>;
    createSelectionMask?(bounds: PSSelectionBounds, docWidth: number, docHeight: number): Promise<any>;
    sendImageToPS?(imageData: string, layerName?: string): Promise<unknown>;
    getValidImages?(): WukongImageLike[];
    getValidImageData?(): string[];
    setSelectionPreview?(data: string): void;
    getFirstImageDimensions?(): { width: number; height: number } | null;
    getImageFromPS?(mode: string): Promise<string | null>;
    displayResults?(...args: unknown[]): void;
  }

  interface RhPsPlaceLike {
    placeImageAtBounds(
      base64: string,
      bounds: PSSelectionBounds,
      layerName?: string,
      placementTarget?: unknown,
      sourceBuffer?: unknown
    ): Promise<unknown> | unknown;
  }

  interface RhPsBridgeLike {
    captureImage(mode: string): Promise<any>;
    importImageResult(output: { url?: string; fileName?: string; id?: string }, options?: Record<string, unknown>): Promise<any>;
  }

  interface RhParserLike {
    normalizeAppId?(value: string): string;
    parseImportedData?(value: unknown): unknown;
    parseAppInfo?(appId: string, result: unknown): any;
  }

  interface RhApiClientLike {
    [key: string]: any;
  }

  interface RhUploadLike {
    [key: string]: any;
  }

  interface RhPollingLike {
    [key: string]: any;
  }

  interface RhRunnerLike {
    [key: string]: any;
  }

  interface RhStoreLike {
    [key: string]: any;
  }

  interface PSCommunicationLike {
    autoExpandCanvas?: boolean;
    lastSelectionInfo?: PSSelectionInfo | null;
    checkConnection(): Promise<boolean>;
    showNotification(message: string, type?: string): void;
    getDocumentInfo(): Promise<PSDocumentInfo>;
    hasSelection(): Promise<PSSelectionInfo>;
    exportSelection(): Promise<PSExportSelectionResult>;
    sendImageToPS(imageData: string, layerName?: string): Promise<unknown>;
    createNewDocument(width: number, height: number, name?: string): Promise<unknown>;
    stretchToCanvas(): Promise<unknown>;
    setLayerVisibility(layerName: string, visible: boolean): Promise<boolean>;
    setLayerVisibilityById?(layerId: number | string, visible: boolean): Promise<unknown>;
    placeImageInSelectionJsxLike(
      imageData: string,
      bounds: PSSelectionBounds,
      layerName?: string
    ): Promise<unknown>;
    placeImageWithEdgeFeather?(
      imageData: string,
      bounds: PSSelectionBounds,
      layerName?: string,
      featherRadius?: number
    ): Promise<unknown>;
    placeImageBananaStyle?(
      imageData: string,
      options?: Record<string, unknown>
    ): Promise<unknown>;
  }

  interface CepLike {
    util: {
      addEventListener?(eventName: string, listener: (event: { data: unknown }) => void): void;
      dispatchEvent?(eventName: string, payload: unknown): void;
    };
  }

  interface PaymentQueryResult<TData = unknown> {
    success: boolean;
    data?: TData;
    message?: string;
    code?: number;
    expired?: boolean;
  }

  interface PaymentServiceLike {
    createOrder(amountYuan: number): Promise<PaymentQueryResult<WukongPaymentOrderData>>;
    queryOrder(orderNo: string): Promise<PaymentQueryResult<WukongPaymentOrderData>>;
    getUserInfo(): Promise<PaymentQueryResult<WukongCurrentUserInfo>>;
    startPolling(
      orderNo: string,
      onSuccess: (data: WukongPaymentOrderData) => void,
      onFailed: (status: unknown, data: unknown) => void,
      onPolling?: (status: unknown, data: unknown) => void
    ): void;
    stopPolling(): void;
  }

  interface Window {
    __wukongPluginAvailability?: PluginAvailabilityState;
    LOCALE_DATA?: Record<string, Record<string, string>>;
    debugManager?: DebugManagerLike;
    wukongApiConfig?: RegionDetectorLike;
    /** @deprecated 兼容旧代码，固定映射到 wukongApiConfig */
    regionDetector?: RegionDetectorLike;
    pluginGateManager?: PluginGateManagerLike;
    authService?: AuthServiceLike;
    paymentService?: PaymentServiceLike;
    keyValidator?: KeyValidatorLike;
    announcementManager?: AnnouncementManagerLike;
    pluginUpdateManager?: PluginUpdateManagerLike;
    wukongStorage?: WukongStorageLike;
    presetManager?: PresetManagerLike;
    sdAPI?: SDAPILike;
    geminiAPI?: GeminiAPILike;
    i18n?: I18nLike;
    t?: (key: string, params?: Record<string, string | number>) => string;
    app?: MainAppLike;
    mainApp?: MainAppLike;
    ecommercePanel?: EcommercePanelLike;
    rhApp?: RHAppLike;
    RHUI?: {
      new (): RHAppLike;
    };
    imageHandler?: ImageHandlerLike;
    rhParser?: RhParserLike;
    rhApiClient?: RhApiClientLike;
    rhUpload?: RhUploadLike;
    rhPolling?: RhPollingLike;
    rhRunner?: RhRunnerLike;
    rhStore?: RhStoreLike;
    rhPsPlace?: RhPsPlaceLike;
    rhPsBridge?: RhPsBridgeLike;
    cep?: CepLike;
    debugLog?: (...args: unknown[]) => void;
    Jimp?: any;
    psComm?: PSCommunicationLike;
    QRCode?: QRCodeLike;
    initRHModules?: () => Promise<RHAppLike | null>;
    initWKModules?: () => unknown;
    initQuickFunctions?: () => void;
    getSelectedQuickFunctionPrompt?: () => string;
    refreshQuickFunctionsI18n?: () => void;
    syncPromptPresetLock?: () => void;
    debugLoadPresets?: () => unknown;
    debugForceUpdate?: () => unknown;
    debugTestPreset?: () => unknown;
    debugVerifySelector?: () => unknown;
    debugForceShow?: () => unknown;
    debugRecreate?: () => unknown;
    debugButtonSelector?: () => unknown;
    debugCheckQuota?: () => unknown;
    debugUpdateQuota?: (...args: unknown[]) => unknown;
    debugStartQuotaRefresh?: () => unknown;
    debugStopQuotaRefresh?: () => unknown;
    debugSetQuotaInterval?: (...args: unknown[]) => unknown;
    debugAspectRatioSupport?: () => unknown;
    simpleSelectionHandler?: any;
    DEBUG_MODE?: boolean;
    placeImageInSelectionNanoStyle?: (
      imageData: string,
      bounds: PSSelectionBounds,
      channelName?: string | null,
      nanoBoundaries?: unknown,
      layerNameOverride?: string | null
    ) => Promise<unknown> | unknown;
    RH_EVENTS?: Record<string, string>;
    emitRhEvent?: (name: string, detail?: unknown) => void;
    localeManager?: LocaleManagerLike;
    apiManager?: WKApiManagerLike;
    connectionManager?: WKConnectionManagerLike;
    ConnectionManager?: {
      new (...args: any[]): WKConnectionManagerLike;
    };
    licenseManager?: WKLicenseManagerLike;
    LicenseManager?: {
      new (...args: any[]): WKLicenseManagerLike;
    };
    generationController?: WKGenerationControllerLike;
    GenerationController?: {
      new (...args: any[]): WKGenerationControllerLike;
    };
    workflowLoader?: WKWorkflowLoaderLike;
    WorkflowLoader?: {
      new (...args: any[]): WKWorkflowLoaderLike;
    };
    UIController?: {
      new (...args: any[]): WKUIControllerLike;
    };
    comfyWKController?: WKComfyControllerLike;
    imageOperationsI18n?: ImageOperationsI18nLike;
    ImageOperations?: ImageOperationsLike;
    ScriptBase?: ScriptBaseLike;
    psapiBridge?: PsapiBridgeLike;
    psWebUI?: PSWebUILike;
    psAPIStatus?: PSAPIStatusLike;
    psOperationsModule?: PSOperationsModuleLike;
    utilsModule?: UtilsModuleLike;
    pageCoordinator?: PageCoordinatorLike;
    uiController?: WKUIControllerLike;
    SettingsManager?: {
      new (...args: any[]): WKSettingsManagerLike;
    };
    WorkflowListManager?: {
      new (...args: any[]): WKWorkflowListManagerLike;
    };
    pluginInstallPath?: string;
    wkInstances?: WKInstancesLike;
    APIManager?: {
      new (...args: any[]): WKApiManagerLike;
    };
    wukongDiagnostics?: WukongDiagnosticsLike;
    debugExportDiagnostics?: () => void;
    updateEcPriceDisplay?: () => void;
    WidgetFactory?: WidgetFactoryLike;
    SeedManager?: SeedManagerLike;
    ImagePreviewManager?: ImagePreviewManagerLike;
    imageWidgetStates?: Record<string, any>;
    ImageUploadWidget?: new (...args: any[]) => any;
  }

  const debugManager: DebugManagerLike;
  const t: (key: string, params?: Record<string, string | number>) => string;
  const io: any;
  function fanxingChat(...args: unknown[]): Promise<any>;
  function fanxingGenerateOnce(...args: unknown[]): Promise<any>;

  function decodeProviderUrl(encoded: string): string;
  const require: any;
}
