var w = { CEB_API_BASE: "https://matilda-nu-one.vercel.app" };
const y = w.CEB_API_BASE, T = `${y}/api/forge`, h = `${y}/api/opportunities`, l = {
  status: "idle",
  lines: [],
  tags: [],
  skills: [],
  sableFile: "",
  zipBase64: "",
  repoName: "",
  ideas: [],
  remaining: 50
};
chrome.runtime.onMessage.addListener((e, a, t) => {
  if (console.log("[Matilda Background] Message received:", e.type, e.owner ? `${e.owner}/${e.repo}` : ""), e.type === "START_SCAN")
    return m(e.owner, e.repo).then(() => t({ ok: !0 })), !0;
  if (e.type === "RESET_STATE" && (chrome.storage.local.set({ scanState: l }), t({ ok: !0 })), e.type === "RETRY_OPPORTUNITIES")
    return b().then(() => t({ ok: !0 })), !0;
});
async function m(e, a) {
  await chrome.storage.local.set({
    scanState: { ...l, status: "scanning", repoName: `${e}/${a}` }
  }), i({ type: "SCAN_STARTED" });
  try {
    const t = await fetch(T, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ owner: e, repo: a })
    });
    if (t.status === 429) {
      await s({ status: "rate_limited", remaining: 0 }), i({ type: "RATE_LIMITED" });
      return;
    }
    if (!t.ok)
      throw new Error(`HTTP ${t.status}`);
    const u = t.body.getReader(), r = new TextDecoder();
    let o = "", p = "";
    for (; ; ) {
      const { done: f, value: g } = await u.read();
      if (f) break;
      o += r.decode(g, { stream: !0 });
      const d = o.split(`
`);
      o = d.pop() || "";
      for (const E of d)
        if (E.startsWith("data: "))
          try {
            const c = JSON.parse(E.slice(6));
            await _(c), c.type === "content" && (p += c.text);
          } catch {
          }
    }
    S(p, `${e}/${a}`);
  } catch (t) {
    await s({
      status: "error",
      error: t.message ?? "Scan failed. Please try again."
    }), i({ type: "SCAN_ERROR", error: t.message });
  }
}
async function _(e) {
  const a = await n();
  switch (e.type) {
    case "status":
      await s({
        remaining: e.remaining ?? a.remaining,
        lines: [
          ...a.lines,
          { type: "status", text: e.message, cls: "blue" }
        ]
      });
      break;
    case "stack":
      await s({ tags: e.tags });
      break;
    case "skills":
      await s({ skills: e.skills });
      break;
    case "content":
      await s({ sableFile: a.sableFile + e.text });
      break;
    case "done":
      await s({
        status: "done",
        zipBase64: e.zipBase64,
        sableFile: e.sableFile,
        tags: e.tags,
        skills: e.skills,
        remaining: e.remaining ?? a.remaining,
        lines: [
          ...a.lines,
          { type: "done", text: "→ Complete ✓", cls: "green" }
        ]
      });
      break;
    case "error":
      await s({ status: "error", error: e.message });
      break;
  }
  i({ type: "STATE_UPDATE", data: e });
}
async function S(e, a) {
  try {
    const t = await n(), r = await (await fetch(h, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sableFile: e, repoName: a, stack: t.tags })
    })).json();
    if (r.error) {
      await s({ ideasError: `Failed: ${r.error}` }), i({ type: "IDEAS_ERROR", error: r.error });
      return;
    }
    await s({ ideas: r.ideas, ideasError: void 0 }), i({ type: "IDEAS_READY", ideas: r.ideas });
  } catch (t) {
    await s({ ideasError: (t == null ? void 0 : t.message) ?? "Failed to generate opportunities" }), i({ type: "IDEAS_ERROR", error: t == null ? void 0 : t.message });
  }
}
async function b() {
  const e = await n();
  !e.sableFile || !e.repoName || (await s({ ideasError: void 0 }), await S(e.sableFile, e.repoName));
}
async function n() {
  return (await chrome.storage.local.get("scanState")).scanState ?? l;
}
async function s(e) {
  const a = await n();
  await chrome.storage.local.set({ scanState: { ...a, ...e } });
}
function i(e) {
  chrome.runtime.sendMessage(e).catch(() => {
  });
}
