import v from "node:https";
function b(i, d) {
  const p = new v.Agent({ rejectUnauthorized: !1 }), m = (s) => {
    try {
      const t = new URL(s).hostname.toLowerCase();
      return t === "localhost" || t === "127.0.0.1" || t === "::1" || t.startsWith("192.168.") || t.startsWith("10.") || t.startsWith("172.16.") || t.startsWith("172.17.") || t.startsWith("172.18.") || t.startsWith("172.19.") || t.startsWith("172.20.") || t.startsWith("172.21.") || t.startsWith("172.22.") || t.startsWith("172.23.") || t.startsWith("172.24.") || t.startsWith("172.25.") || t.startsWith("172.26.") || t.startsWith("172.27.") || t.startsWith("172.28.") || t.startsWith("172.29.") || t.startsWith("172.30.") || t.startsWith("172.31.");
    } catch {
      return !1;
    }
  }, c = (s, e) => {
    const t = {
      headers: e || {}
    };
    return s.startsWith("https://") && m(s) && (t.agent = p), t;
  }, l = async (s, e) => {
    try {
      const t = await fetch(s, {
        ...c(s, {
          // Important: explicitly request correct type so normal servers don't return HTML
          Accept: e === "robots" ? "text/plain" : "application/xml, text/xml"
        })
      }), r = t.headers.get("content-type") || "", o = await t.text(), a = o.trim();
      if (r.includes("text/html") || a.toLowerCase().startsWith("<!doctype html") || a.toLowerCase().startsWith("<html"))
        return {
          exists: !1,
          status: t.status,
          // Probably 200, but actually not the right file
          url: s,
          error: "SPA Fallback detected (Received HTML instead of file)",
          size: o.length
        };
      let g = !0, w = "";
      return e === "robots" ? a.toLowerCase().includes("user-agent:") || (g = !1, w = 'Invalid content: missing "User-agent" directive') : e === "sitemap" && !a.startsWith("<?xml") && !a.includes("<urlset") && !a.includes("<sitemapindex") && (g = !1, w = "Invalid content: doesn't look like an XML sitemap"), t.ok ? g ? {
        exists: !0,
        status: t.status,
        url: s,
        size: o.length,
        contentSnippet: o.substring(0, 200) + (o.length > 200 ? "..." : "")
      } : {
        exists: !0,
        // File physically exists, but it's "broken"
        status: t.status,
        url: s,
        size: o.length,
        contentSnippet: o.substring(0, 100),
        warning: w
        // Pass as warning
      } : {
        exists: !1,
        status: t.status,
        url: s,
        error: `HTTP ${t.status}`
      };
    } catch (t) {
      return {
        exists: !1,
        status: 0,
        url: s,
        error: t instanceof Error ? t.message : String(t)
      };
    }
  };
  i.handle("seo:check-server-files", async (s) => {
    const t = (typeof s == "string" ? s : String(s)).replace(/\/$/, ""), [r, o] = await Promise.all([
      l(`${t}/robots.txt`, "robots"),
      l(`${t}/sitemap.xml`, "sitemap")
    ]);
    return { robots: r, sitemap: o };
  }), i.handle("seo:fetch-file", async (s) => {
    const e = typeof s == "string" ? s : String(s);
    try {
      const t = await fetch(e, {
        method: "GET",
        ...c(e)
      });
      if (!t.ok) throw new Error(`Status ${t.status}`);
      const r = await t.text();
      return {
        success: !0,
        content: r,
        contentType: t.headers.get("content-type") || "text/plain",
        size: r.length
      };
    } catch (t) {
      return {
        success: !1,
        error: t instanceof Error ? t.message : String(t)
      };
    }
  }), i.handle("seo:get-raw-html", async (s) => {
    const e = s;
    if (typeof e != "string")
      return { success: !1, error: "Invalid URL provided", html: "" };
    try {
      const t = await fetch(e, {
        ...c(e, {
          // Pretend to be a normal browser or bot so server doesn't get scared
          "User-Agent": "U-DevTools-SEO-Scanner/1.0",
          Accept: "text/html"
        })
      });
      if (!t.ok) throw new Error(`Status ${t.status}`);
      return { success: !0, html: await t.text() };
    } catch (t) {
      return {
        success: !1,
        error: t instanceof Error ? t.message : String(t),
        html: ""
      };
    }
  }), i.handle("seo:scan-headers", async (s) => {
    const e = typeof s == "string" ? s : String(s);
    if (!e)
      return { success: !1, error: "Invalid URL provided" };
    try {
      const t = await fetch(e, {
        method: "HEAD",
        ...c(e, {
          "User-Agent": "U-DevTools-SEO-Scanner/1.0"
        })
      }), r = {};
      return t.headers.forEach((o, a) => {
        r[a.toLowerCase()] = o;
      }), {
        success: !0,
        headers: r,
        status: t.status
      };
    } catch (t) {
      return {
        success: !1,
        error: t instanceof Error ? t.message : String(t)
      };
    }
  }), i.handle("seo:check-link", async (s) => {
    const e = typeof s == "string" ? s : String(s);
    if (!e)
      return { success: !1, error: "Invalid URL provided" };
    try {
      const t = await fetch(e, {
        method: "HEAD",
        redirect: "manual",
        // Important: don't follow redirect automatically
        ...c(e, {
          "User-Agent": "U-DevTools-SEO-Scanner/1.0"
        })
      });
      let r = t.status, o;
      if (r >= 300 && r < 400)
        o = t.headers.get("location") || void 0;
      else if (r === 405) {
        const a = await fetch(e, {
          method: "GET",
          redirect: "manual",
          ...c(e, {
            "User-Agent": "U-DevTools-SEO-Scanner/1.0"
          })
        });
        r = a.status, r >= 300 && r < 400 && (o = a.headers.get("location") || void 0);
      }
      return { success: !0, status: r, redirectUrl: o };
    } catch (t) {
      return {
        success: !1,
        error: t instanceof Error ? t.message : String(t)
      };
    }
  }), i.handle("seo:check-robots", async (s) => {
    const { url: e, robotsTxt: t } = s;
    if (typeof e != "string" || typeof t != "string")
      return {
        isAllowed: !0,
        reason: "Invalid parameters"
      };
    try {
      const r = new URL(e).pathname, o = y(t, r);
      return {
        isAllowed: o.isAllowed,
        reason: o.reason,
        rules: o.rules
      };
    } catch (r) {
      return {
        isAllowed: !0,
        reason: r instanceof Error ? r.message : "Unknown error"
      };
    }
  });
  let n = null, h = null;
  const f = async (s) => {
    if (!n)
      try {
        const { createUnlighthouse: e } = await import("@unlighthouse/core"), { createServer: t } = await import("@unlighthouse/server");
        n = await e(
          {
            root: d.root,
            site: s,
            scanner: {
              device: "desktop",
              skipJavascript: !1,
              samples: 1
            },
            debug: !0
          },
          { name: "u-devtools" }
        );
        const { server: r, app: o } = await t();
        h = { server: r, app: o }, await n.setServerContext({
          url: r.url || "http://localhost:5678",
          server: r.server,
          // listhen server instance
          app: o
          // h3 app instance
        }), n.hooks.hook("task-started", (a) => {
          i.broadcast("seo:unlighthouse-update", {
            path: a,
            status: "in-progress"
          });
        }), n.hooks.hook("task-complete", (a, u) => {
          const g = u.report?.categories ? {
            performance: u.report.categories.performance?.score ?? null,
            accessibility: u.report.categories.accessibility?.score ?? null,
            "best-practices": u.report.categories["best-practices"]?.score ?? null,
            seo: u.report.categories.seo?.score ?? null,
            pwa: u.report.categories.pwa?.score ?? null
          } : null;
          i.broadcast("seo:unlighthouse-update", {
            path: a,
            status: "completed",
            score: g,
            seo: u.seo
          });
        }), n.hooks.hook("worker-finished", () => {
          i.broadcast("seo:unlighthouse-finished", {});
        });
      } catch (e) {
        throw console.error("[U-DevTools:SEO] Unlighthouse not available:", e), e;
      }
  };
  i.handle("seo:unlighthouse-start", async (s) => {
    const e = s;
    if (typeof e != "string")
      return { success: !1, error: "Invalid URL provided" };
    try {
      return await f(e), n.setSiteUrl(e), await n.start(), { success: !0 };
    } catch (t) {
      return {
        success: !1,
        error: t instanceof Error ? t.message : "Unlighthouse not available"
      };
    }
  }), i.handle("seo:unlighthouse-get-reports", async () => {
    if (!n) return [];
    try {
      const s = n.worker.routeReports || [];
      return Array.from(s.values()).map((e) => ({
        id: e.reportId,
        path: e.route.path,
        status: e.tasks.runLighthouseTask ? "completed" : "waiting",
        score: e.report?.categories ? {
          performance: e.report.categories.performance?.score ?? null,
          accessibility: e.report.categories.accessibility?.score ?? null,
          "best-practices": e.report.categories["best-practices"]?.score ?? null,
          seo: e.report.categories.seo?.score ?? null,
          pwa: e.report.categories.pwa?.score ?? null
        } : null,
        seo: e.seo
      }));
    } catch (s) {
      return console.error("[U-DevTools:SEO] Failed to get reports:", s), [];
    }
  });
}
function y(i, d, p = "Googlebot") {
  const m = i.split(`
`);
  let c = "", l = !1;
  const n = [];
  let h = 0, f = "";
  return m.forEach((s, e) => {
    const t = s.split("#")[0].trim();
    if (!t) return;
    const [r, ...o] = t.split(":"), a = o.join(":").trim();
    r.toLowerCase() === "user-agent" ? c = a : r.toLowerCase() === "disallow" && (c === "*" || c.includes(p)) ? a === "" ? (l = !1, h = 0, f = "") : d.startsWith(a) && (l = !0, h = e + 1, f = `Disallow: ${a}`, n.push({ line: e + 1, rule: `Disallow: ${a}` })) : r.toLowerCase() === "allow" && (c === "*" || c.includes(p)) && d.startsWith(a) && (l = !1, h = 0, f = "", n.push({ line: e + 1, rule: `Allow: ${a}` }));
  }), {
    isAllowed: !l,
    reason: l && h > 0 ? `Blocked by line ${h}: ${f}` : void 0,
    rules: n.length > 0 ? n : void 0
  };
}
export {
  b as setupServer
};
