// Frontend helper: talks to the local /api/* endpoints that proxy OpenRouter.
// Exposed on window.LS_ai so any JSX file can use it.

(function () {
  async function post(url, body) {
    const res = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body || {}),
    });
    const text = await res.text();
    let data;
    try { data = JSON.parse(text); } catch { data = { error: text }; }
    if (!res.ok) {
      const err = new Error(data.error || `HTTP ${res.status}`);
      err.status = res.status;
      err.data = data;
      throw err;
    }
    return data;
  }

  function fileToBase64(file) {
    return new Promise((resolve, reject) => {
      const r = new FileReader();
      r.onload = () => {
        const s = r.result;
        const comma = s.indexOf(",");
        resolve(comma >= 0 ? s.slice(comma + 1) : s);
      };
      r.onerror = reject;
      r.readAsDataURL(file);
    });
  }

  window.LS_ai = {
    async check({ period, rulesVersion, rows, totals }) {
      return post("/api/ai-check", { period, rulesVersion, rows, totals });
    },
    async ocrWhk(file) {
      const imageBase64 = await fileToBase64(file);
      return post("/api/ocr-whk", {
        imageBase64,
        mimeType: file.type || "application/pdf",
        filename: file.name,
      });
    },
    async explain({ payslip, emp, period }) {
      return post("/api/explain-payslip", { payslip, emp, period });
    },
    async health() {
      const r = await fetch("/api/health");
      return r.json();
    },
  };
})();
