/**
 * What the settings screen actually puts on the page, in the language the
 * person reads. Throwaway. `bun run tmp/settings/render.ts`.
 */

const BASE = "http://127.0.0.1:4214"

async function actionId(path: string, name: string) {
  const html = await fetch(`${BASE}${path}`).then((r) => r.text())
  const chunks = [
    ...new Set(
      [...html.matchAll(/\/_next\/static\/[^"'\\ ]+?\.js/g)].map((m) => m[0]),
    ),
  ]
  const pattern = new RegExp(
    `__next_internal_action_entry_do_not_use__ \\[\\{"([0-9a-f]+)":\\{"name":"${name}"\\}\\}`,
  )
  for (const chunk of chunks) {
    const source = await fetch(`${BASE}${chunk}`).then((r) => r.text())
    const found = source.match(pattern)
    if (found) return found[1]!
  }
  throw new Error("no action id")
}

const SIGN_IN = await actionId("/login", "attemptSignIn")

async function cookieFor(username: string, password: string) {
  const r = await fetch(`${BASE}/login`, {
    method: "POST",
    headers: {
      "Next-Action": SIGN_IN,
      "Content-Type": "text/plain;charset=UTF-8",
    },
    body: JSON.stringify([username, password]),
  })
  return r.headers
    .getSetCookie()
    .map((l) => l.split(";")[0]!)
    .join("; ")
}

const who = process.argv[2] ?? "narin"
const password = process.argv[3] ?? "admin1"

const page = await fetch(`${BASE}/settings`, {
  headers: { cookie: await cookieFor(who, password) },
}).then((r) => r.text())

// Everything between tags, which is close enough to read the screen by.
const text = page
  .replace(/<script[\s\S]*?<\/script>/g, " ")
  .replace(/<style[\s\S]*?<\/style>/g, " ")
  .replace(/<[^>]+>/g, "\n")
  .split("\n")
  .map((line) => line.trim())
  .filter(Boolean)

console.log(`--- ${who} ---`)
console.log(text.slice(-30).join("\n"))
