export interface UploadedJavaFile {
  fileKey: string
  originalFilename: string
  localPath: string
  size: number
  relativePath?: string
}

export interface PywebviewApi {
  close?: () => Promise<void>
  minimize?: () => Promise<void>
  maximize?: () => Promise<void>
  toggle_maximize?: () => Promise<void>
  save_image?: (urlOrData: string, filename?: string) => Promise<{ success: boolean; path?: string; error?: string }>
  save_image_to_folder?: (urlOrData: string, dirPath: string, filename?: string) => Promise<{ success: boolean; path?: string; error?: string }>
  select_folder?: () => Promise<string | null>
  select_brand_xlsx_files?: () => Promise<string[]>
  select_brand_folder?: () => Promise<string | null>
  upload_file_to_java?: (filePath: string, relativePath?: string) => Promise<{ success: boolean; message?: string; data?: UploadedJavaFile; error?: string }>
  save_file_from_url?: (url: string, filename: string) => Promise<{ success: boolean; path?: string; error?: string }>
  save_template_xlsx?: () => Promise<{ success: boolean; path?: string; error?: string }>
  save_template_zip?: () => Promise<{ success: boolean; path?: string; error?: string }>
  enqueue_json?: (data: unknown) => Promise<{ success: boolean; queue_size?: number; error?: string }>
}

declare global {
  interface Window {
    pywebview?: {
      api?: PywebviewApi
    }
  }
}

let cachedPywebviewApi: PywebviewApi | undefined
let pywebviewReadyBound = false

function syncPywebviewApi() {
  cachedPywebviewApi = window.pywebview?.api
  return cachedPywebviewApi
}

function bindPywebviewReady() {
  if (pywebviewReadyBound || typeof window === 'undefined' || !window.addEventListener) return
  pywebviewReadyBound = true
  window.addEventListener('pywebviewready', () => {
    syncPywebviewApi()
  })
}

bindPywebviewReady()

export function getPywebviewApi() {
  return syncPywebviewApi() || cachedPywebviewApi
}

export function hasPywebview() {
  return Boolean(getPywebviewApi())
}
