/** Max file size for WS base64 push (keeps command payloads reasonable). */
export const DESKTOP_PUSH_MAX_BYTES = 8 * 1024 * 1024;

export function desktopPathHint(platform?: string): string {
  switch (platform?.toLowerCase()) {
    case 'windows':
      return '%USERPROFILE%\\Desktop\\';
    case 'darwin':
      return '~/Desktop/';
    case 'linux':
      return '~/Desktop/ (or XDG DESKTOP)';
    default:
      return 'Desktop (auto-detected per OS)';
  }
}

export function readFileAsBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    if (file.size > DESKTOP_PUSH_MAX_BYTES) {
      reject(new Error(`File exceeds ${DESKTOP_PUSH_MAX_BYTES / (1024 * 1024)}MB limit for push`));
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      const b64 = result.includes(',') ? result.split(',')[1] : result;
      if (!b64) {
        reject(new Error('Could not read file'));
        return;
      }
      resolve(b64);
    };
    reader.onerror = () => reject(reader.error ?? new Error('read failed'));
    reader.readAsDataURL(file);
  });
}

export async function pushFileToAgentDesktop(
  send: (action: string, args?: { path?: string; data?: string; command?: string }) => Promise<unknown>,
  file: File,
  remoteName?: string
): Promise<void> {
  const b64 = await readFileAsBase64(file);
  const name = (remoteName?.trim() || file.name).replace(/\\/g, '/');
  await send('push_desktop', { path: name, data: b64 });
}
