const API_ROOT = '/api';

async function request(path, options = {}) {
  const response = await fetch(`${API_ROOT}${path}`, {
    credentials: 'same-origin',
    ...options,
    headers: {
      ...(options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
      ...(options.headers || {}),
    },
  });

  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(data.error || `Request failed (${response.status})`);
    error.status = response.status;
    error.data = data;
    throw error;
  }
  return data;
}

function makeEntity(name) {
  const root = `/entities/${encodeURIComponent(name)}`;
  return {
    list: (sort = '-created_date', limit = 500) =>
      request(`${root}?sort=${encodeURIComponent(sort)}&limit=${limit}`),
    filter: (filters = {}) =>
      request(`${root}?filter=${encodeURIComponent(JSON.stringify(filters))}`),
    create: (record) => request(root, { method: 'POST', body: JSON.stringify(record) }),
    update: (id, changes) => request(`${root}/${encodeURIComponent(id)}`, {
      method: 'PATCH', body: JSON.stringify(changes),
    }),
    delete: (id) => request(`${root}/${encodeURIComponent(id)}`, { method: 'DELETE' }),
    bulkUpdate: (updates) => request(`${root}/bulk`, {
      method: 'PATCH', body: JSON.stringify({ updates }),
    }),
  };
}

async function uploadFile({ file }) {
  const data = await new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(',')[1] || '');
    reader.onerror = () => reject(reader.error || new Error('Could not read image'));
    reader.readAsDataURL(file);
  });
  return request('/uploads', {
    method: 'POST', body: JSON.stringify({ name: file.name, type: file.type, data }),
  });
}

export const shire = {
  auth: {
    isAuthenticated: async () => true,
    me: async () => ({ id: 'local-owner', email: 'local@shire3d', role: 'owner', local: true }),
    logout: async (redirect) => {
      if (redirect) window.location.href = typeof redirect === 'string' ? redirect : '/';
    },
    loginViaEmailPassword: async () => ({ success: true }),
    redirectToLogin: () => { window.location.href = '/'; },
  },
  entities: new Proxy({}, { get: (_, name) => makeEntity(String(name)) }),
  functions: {
    invoke: async (name, payload = {}) => ({ data: await request(`/actions/${name}`, {
      method: 'POST', body: JSON.stringify(payload),
    }) }),
  },
  integrations: {
    Core: {
      UploadFile: uploadFile,
      InvokeLLM: (payload) => request('/ai/generate', {
        method: 'POST', body: JSON.stringify(payload),
      }),
    },
  },
  assistant: {
    chat: (message) => request('/assistant/chat', {
      method: 'POST', body: JSON.stringify({ message }),
    }),
    status: () => request('/assistant/status'),
  },
};
