const BASE = '/api/arduino';

export async function checkArduinoCli() {
  const res = await fetch(`${BASE}/status`);
  if (!res.ok) throw new Error('Arduino CLI server not reachable');
  return res.json();
}

export async function listBoards() {
  const res = await fetch(`${BASE}/boards`);
  if (!res.ok) throw new Error('Failed to list boards');
  return res.json();
}

export async function compileAndUpload(code, port, fqbn) {
  const res = await fetch(`${BASE}/upload`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code, port, fqbn }),
  });
  const data = await res.json();
  if (!res.ok) {
    throw new Error(data.error || 'Compile/upload failed');
  }
  return data;
}

export async function compileOnly(code) {
  const res = await fetch(`${BASE}/compile`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code }),
  });
  const data = await res.json();
  if (!res.ok) {
    throw new Error(data.error || 'Compilation failed');
  }
  return data;
}
