import { join, basename } from "node:path";
import { existsSync } from "node:fs";
class WordPressDetector {
  name = "wordpress";
  language = "php";
  filePattern = /\.php$/;
  // Standard WP template hierarchy files
  static TEMPLATE_FILES = /* @__PURE__ */ new Set([
    "front-page.php",
    "home.php",
    "single.php",
    "page.php",
    "archive.php",
    "category.php",
    "tag.php",
    "taxonomy.php",
    "search.php",
    "404.php",
    "index.php"
  ]);
  async detect(projectRoot, files) {
    const hasWpDir = files.some((f) => f.startsWith("wp-content/") || f.includes("/wp-content/"));
    if (hasWpDir) return true;
    if (files.some((f) => f === "wp-config.php" || f.endsWith("/wp-config.php"))) {
      return true;
    }
    const wpConfig = join(projectRoot, "wp-config.php");
    if (existsSync(wpConfig)) return true;
    return files.some((f) => f.includes("wp-content/") || f.includes("wp-includes/"));
  }
  async extractRoutes(filePath, content, ctx) {
    const routes = [];
    const fileName = basename(filePath);
    if (WordPressDetector.TEMPLATE_FILES.has(fileName)) {
      let pathVal = "/" + fileName.replace(/\.php$/, "");
      if (fileName === "front-page.php") {
        pathVal = "/";
      }
      routes.push({
        framework: this.name,
        method: "GET",
        path: pathVal,
        handlerFile: filePath,
        handlerSymbol: fileName,
        metadata: {
          confidence: "inferred",
          routeType: "server",
          templateFile: fileName
        }
      });
    }
    const restRegex = /register_rest_route\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g;
    let match;
    while ((match = restRegex.exec(content)) !== null) {
      const namespace = match[1];
      const routePath = match[2];
      const fullPath = `/wp-json/${namespace.replace(/^\/|\/$/g, "")}/${routePath.replace(/^\/|\/$/g, "")}`;
      const scanWindow = content.substring(match.index, match.index + 1e3);
      const callbackMatch = scanWindow.match(/'callback'\s*=>\s*(?:['"]([^'"]+)['"]|\[\s*(?:['"]?([a-zA-Z0-9_]+)['"]?|([$]this))\s*,\s*['"]([^'"]+)['"]\s*\])/);
      let handlerSymbol = "rest_callback";
      if (callbackMatch) {
        if (callbackMatch[1]) {
          handlerSymbol = callbackMatch[1];
        } else {
          const className = callbackMatch[2] || "this";
          const methodName = callbackMatch[4];
          handlerSymbol = `${className}::${methodName}`;
        }
      }
      let verbs = ["GET"];
      const methodsMatch = scanWindow.match(/'methods'\s*=>\s*(?:['"]([^'"]+)['"]|WP_REST_Server::([A-Z_]+)|\[\s*([^\]]+)\s*\])/);
      if (methodsMatch) {
        if (methodsMatch[1]) {
          verbs = [methodsMatch[1].toUpperCase()];
        } else if (methodsMatch[2]) {
          const constant = methodsMatch[2];
          if (constant === "READABLE") verbs = ["GET"];
          else if (constant === "CREATABLE") verbs = ["POST"];
          else if (constant === "EDITABLE") verbs = ["PUT", "PATCH"];
          else if (constant === "DELETABLE") verbs = ["DELETE"];
          else verbs = ["ALL"];
        } else if (methodsMatch[3]) {
          verbs = methodsMatch[3].split(",").map((v) => v.trim().replace(/['"]/g, "").toUpperCase());
        }
      }
      let resolvedFile = filePath;
      const resolvedPath = ctx.resolveSymbolToFile(handlerSymbol.split("::")[0]);
      if (resolvedPath) {
        resolvedFile = resolvedPath;
      }
      for (const verb of verbs) {
        routes.push({
          framework: this.name,
          method: verb,
          path: fullPath,
          handlerFile: resolvedFile,
          handlerSymbol,
          metadata: {
            confidence: "inferred",
            routeType: "server"
          }
        });
      }
    }
    return routes;
  }
  async extractHooks(filePath, content, ctx) {
    const hooks = [];
    const hookRegex = /\badd_(action|filter|shortcode)\s*\(\s*['"]([^'"]+)['"]\s*,\s*(?:['"]([^'"]+)['"]|\[\s*(?:['"]?([a-zA-Z0-9_]+)['"]?|([$]this))\s*,\s*['"]([^'"]+)['"]\s*\])/g;
    let match;
    while ((match = hookRegex.exec(content)) !== null) {
      const type = match[1];
      const hookName = match[2];
      let handlerSymbol = "callback";
      if (match[3]) {
        handlerSymbol = match[3];
      } else {
        const className = match[4] || "this";
        const methodName = match[6];
        handlerSymbol = `${className}::${methodName}`;
      }
      hooks.push({
        framework: this.name,
        hookName,
        handlerFile: filePath,
        handlerSymbol,
        hookType: type === "shortcode" ? "shortcode" : type === "filter" ? "filter" : "action"
      });
    }
    const ptRegex = /\bregister_post_type\s*\(\s*['"]([^'"]+)['"]/g;
    while ((match = ptRegex.exec(content)) !== null) {
      const postTypeName = match[1];
      hooks.push({
        framework: this.name,
        hookName: postTypeName,
        handlerFile: filePath,
        handlerSymbol: "register_post_type",
        hookType: "post_type"
      });
    }
    return hooks;
  }
}
export {
  WordPressDetector
};
