import k from "path";
import { fileURLToPath as x } from "url";
import { createRequire as E } from "module";
import { parse as f } from "node-html-parser";
import { toMarkdown as S, u as q } from "@liuli-util/markdown-util";
import { fromHtml as $ } from "hast-util-from-html";
import { toMdast as b } from "hast-util-to-mdast";
import v from "find-cache-dir";
import d from "pathe";
import { pathExists as T, readJson as M, mkdirp as P, writeJson as A } from "fs-extra/esm";
import { writeFile as L, mkdir as C } from "node:fs/promises";
const y = () => x(import.meta.url), _ = () => k.dirname(y()), p = _(), K = y();
const Q = E(import.meta.url);
function H(t) {
  const e = t.match(/\/works\/(\d+)/);
  if (e == null)
    throw new Error(`无法从 ${t} 中提取 id`);
  return e[1];
}
async function D(t) {
  const e = await fetch(`https://archiveofourown.org/works/${t}?view_full_work=true`).then((o) => o.text());
  return I(e).map((o) => ({ ...o, bookId: t }));
}
function F(t) {
  const e = $(t, { fragment: !0 }), o = b(e);
  return S(o);
}
function I(t) {
  return Array.from(f(t).querySelectorAll("#chapters > .chapter")).map((o) => {
    const r = o.querySelector(".title");
    if (!r)
      throw new Error("无法提取章节标题");
    const n = r.querySelector("a");
    if (!n)
      throw new Error("无法提取章节链接");
    const a = n.getAttribute("href")?.match(/\/works\/\d+\/chapters\/(\d+)/)?.[1];
    if (!a)
      throw new Error("无法提取章节 id");
    r.querySelector("a")?.remove();
    const i = r.textContent?.trim().match("^: (.*)$")?.[1];
    if (!i)
      throw new Error("无法提取章节标题");
    const c = o.querySelector(".userstuff.module");
    if (!c)
      throw new Error("无法提取章节内容");
    return c.querySelector(".landmark.heading")?.remove(), {
      id: a,
      title: i,
      content: F(c.innerHTML)
    };
  });
}
function R(t) {
  return {
    name: "ao3",
    async *generate() {
      const e = H(t.url), o = await D(e), r = o.length;
      for (let n = 0; n < o.length; n++) {
        const a = o[n], i = (n + 1).toString().padStart(r, "0");
        yield {
          id: a.id,
          name: i,
          content: "# " + a.title + `

` + a.content,
          path: [i + ".md"],
          resources: [],
          created: Date.now(),
          updated: Date.now()
        };
      }
    }
  };
}
function j(t) {
  const e = /threads\/(?:.*?\.)?(\d+)/.exec(t);
  if (e == null)
    throw new Error(`无法从 ${t} 中提取 id`);
  return e[1];
}
function J(t) {
  const e = t.getAttribute("data-content")?.slice(5);
  if (!e)
    throw new Error("无法提取 id");
  const o = t.querySelector(".threadmarkLabel")?.textContent?.trim();
  if (!o)
    throw new Error("无法提取标题 " + e);
  const r = t.querySelector('time[itemprop="datePublished"]')?.getAttribute("datetime");
  if (!r)
    throw new Error("无法提取创建时间 " + e);
  const n = new Date(r).getTime(), a = t.querySelector('time[itemprop="dateModified"]')?.getAttribute("datetime"), i = a ? new Date(a).getTime() : n, c = t.querySelector(".message-body .bbWrapper")?.innerHTML;
  if (!c)
    throw new Error("无法提取内容 " + e);
  const u = $(c, { fragment: !0 }), m = b(u, {
    // 转换 <br/> 为 \n，ref: https://github.com/syntax-tree/hast-util-to-mdast/issues/66#issuecomment-941930366
    handlers: {
      br() {
        return q("text", `
`);
      }
    }
  });
  return {
    id: e,
    title: o,
    content: S(m),
    created: n,
    updated: i
  };
}
function N(t) {
  const e = f(t);
  return Array.from(e.querySelectorAll(".block-body.js-replyNewMessageContainer > .message")).map(
    J
  );
}
function O(t) {
  const o = f(t).querySelector("input.js-pageJumpPage")?.getAttribute("max");
  return o ? Number.parseInt(o) : 1;
}
async function w(t, e) {
  const o = `https://forums.sufficientvelocity.com/threads/${t}/reader/page-${e}`, r = await fetch(o);
  if (!r.ok)
    throw new Error(`无法获取 ${o} 的内容，状态码为 ${r.status}，${r.statusText}`);
  return r.text();
}
function g() {
  const t = v({ name: "@mark-magic/plugin-ao3" });
  if (!t)
    throw new Error("无法找到缓存目录");
  return d.resolve(t, "sufficientvelocity.json");
}
function U(t) {
  return {
    name: "sufficientvelocity",
    async *generate() {
      let e = {};
      if (t.cached) {
        const r = g();
        await T(r) && Object.assign(e, await M(r));
      }
      async function o(r, n) {
        if (!t.cached)
          return await w(r, n);
        const a = `thread-${r}-page-${n}`;
        return e[a] || (e[a] = await w(r, n)), e[a];
      }
      try {
        const r = j(t.url), n = await o(r, 1), a = O(n), i = ((a - 1) * 10).toString().length;
        for (let c = 1, u = 1; c <= a; c++) {
          const m = await o(r, c), l = N(m);
          if (l.length === 0) {
            const s = `thread-${r}-page-${c}`;
            throw delete e[s], m.includes("Rating limit Exceeded") ? new Error(`无法提取第 ${c} 页，因为超过了论坛的访问速率限制，请稍后再试`) : new Error("无法提取章节");
          }
          await P(d.resolve(p, ".temp")), await L(d.resolve(p, `.temp/${r}-${c}.html`), m);
          for (const s of l) {
            const h = u.toString().padStart(i, "0");
            yield {
              id: s.id,
              name: h,
              content: "# " + s.title + `

` + s.content,
              path: [h + ".md"],
              created: s.created,
              updated: s.updated,
              resources: []
            }, u++;
          }
        }
      } finally {
        if (t.cached) {
          const r = g();
          await C(d.dirname(r), { recursive: !0 }), await A(r, e);
        }
      }
    }
  };
}
const B = {
  ao3: R,
  sufficientvelocity: U
};
function nt(t) {
  return B[t.site](t);
}
export {
  nt as input
};
