#!/usr/bin/env bun
// cdp-read — evaluate one JS expression in the attached Chrome page and print
// the raw string result to stdout.
//
// Designed to be piped straight into `secretctl add NAME`, so a harvested API
// key never appears in an agent transcript or shell history.
//
//   cdp-read '<expression>'            # first page target
//   cdp-read --url=groq '<expression>' # target whose URL contains "groq"
//   cdp-read --port=9222 ...
//
// Exit codes: 0 ok, 1 CDP error / expression threw, 2 usage.

const args = process.argv.slice(2);
let port = 9222;
let urlMatch = "";
let envVar = "";
const exprParts = [];
for (const a of args) {
  if (a.startsWith("--port=")) port = Number(a.slice(7));
  else if (a.startsWith("--url=")) urlMatch = a.slice(6);
  else if (a.startsWith("--env=")) envVar = a.slice(6);
  else if (a === "-h" || a === "--help") {
    console.log("usage: cdp-read [--port=9222] [--url=substring] [--env=VAR] '<js expression>'\n  __VALUE__ in the expression is replaced by JSON(process.env[VAR]).");
    process.exit(0);
  } else exprParts.push(a);
}
const expression = exprParts.join(" ").replaceAll("__VALUE__", JSON.stringify(envVar ? (process.env[envVar] ?? "") : ""));
if (!expression) {
  console.error("cdp-read: missing expression");
  process.exit(2);
}

const list = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
const pages = list.filter((t) => t.type === "page");
const page =
  (urlMatch && pages.find((t) => t.url.includes(urlMatch))) || pages[0];
if (!page) {
  console.error("cdp-read: no page target found");
  process.exit(1);
}

const ws = new WebSocket(page.webSocketDebuggerUrl);
let id = 0;
const pending = new Map();
const send = (method, params = {}) =>
  new Promise((resolve, reject) => {
    const msgId = ++id;
    pending.set(msgId, { resolve, reject });
    ws.send(JSON.stringify({ id: msgId, method, params }));
  });

ws.onmessage = (e) => {
  let msg;
  try { msg = JSON.parse(String(e.data)); } catch { return; }
  const p = pending.get(msg.id);
  if (!p) return;
  pending.delete(msg.id);
  if (msg.error) p.reject(new Error(msg.error.message));
  else p.resolve(msg.result);
};

const done = new Promise((resolve) => {
  ws.onopen = async () => {
    try {
      const r = await send("Runtime.evaluate", {
        expression,
        returnByValue: true,
        awaitPromise: true,
        userGesture: true,
      });
      if (r.exceptionDetails) {
        console.error("cdp-read: " + (r.exceptionDetails.exception?.description || "expression threw"));
        resolve(1);
      } else if (r.result?.subtype === "error") {
        console.error("cdp-read: " + r.result.description);
        resolve(1);
      } else {
        process.stdout.write(String(r.result?.value ?? ""));
        resolve(0);
      }
    } catch (e) {
      console.error("cdp-read: " + e.message);
      resolve(1);
    }
    ws.close();
  };
  ws.onerror = () => resolve(1);
});

const code = await done;
process.exit(code);
