"use strict";

function parseProductIdentity(versionPayload, html) {
  const version =
    typeof versionPayload === "string"
      ? JSON.parse(versionPayload).version
      : versionPayload.version;
  const author =
    html.match(
      /<meta\s+name=["']author["']\s+content=["']([^"']+)["']/i,
    )?.[1] ?? "";
  const normalizedAuthor = author.toLowerCase();
  let product = "UNKNOWN";
  if (normalizedAuthor.includes("forgejo")) product = "FORGEJO";
  if (normalizedAuthor.includes("gitea")) product = "GITEA";
  return { product, version, author };
}

async function inspectProduct(baseUrl, fetchImpl = fetch) {
  const normalizedBase = baseUrl.replace(/\/+$/, "");
  const [versionResponse, homeResponse] = await Promise.all([
    fetchImpl(`${normalizedBase}/api/v1/version`),
    fetchImpl(`${normalizedBase}/`),
  ]);
  if (!versionResponse.ok || !homeResponse.ok) {
    throw new Error(
      `repository identity probe failed: version=${versionResponse.status}, home=${homeResponse.status}`,
    );
  }
  return parseProductIdentity(
    await versionResponse.json(),
    await homeResponse.text(),
  );
}

async function main() {
  const baseUrl =
    process.argv[2] ?? "https://guanghulab.com/fifth-domain";
  const expectedProduct = (process.argv[3] ?? "FORGEJO").toUpperCase();
  const identity = await inspectProduct(baseUrl);
  process.stdout.write(`${JSON.stringify(identity, null, 2)}\n`);
  if (identity.product !== expectedProduct) {
    process.stderr.write(
      `PRODUCT_IDENTITY_MISMATCH: expected ${expectedProduct}, got ${identity.product} ${identity.version}\n`,
    );
    process.exitCode = 2;
  }
}

if (require.main === module) {
  main().catch((error) => {
    process.stderr.write(`${error.message}\n`);
    process.exitCode = 1;
  });
}

module.exports = { inspectProduct, parseProductIdentity };
