import { join, basename } from "node:path";
import { existsSync } from "node:fs";
class DrupalDetector {
  name = "drupal";
  language = "php";
  filePattern = /\.(yml|module|php)$/;
  async detect(projectRoot, files) {
    const corePath = join(projectRoot, "core/lib/Drupal.php");
    if (existsSync(corePath)) return true;
    const hasRoutingYml = files.some((f) => f.endsWith(".routing.yml"));
    if (hasRoutingYml) return true;
    return false;
  }
  async extractRoutes(filePath, content, ctx) {
    const routes = [];
    if (!filePath.endsWith(".routing.yml")) {
      return [];
    }
    const lines = content.split("\n");
    let currentRouteId = "";
    let currentPath = "";
    let currentController = "";
    for (const line of lines) {
      const routeMatch = line.match(/^([a-z0-9_.-]+):/);
      if (routeMatch) {
        if (currentPath && currentController) {
          routes.push(this.createRouteBinding(currentPath, currentController, filePath, ctx));
        }
        currentRouteId = routeMatch[1];
        currentPath = "";
        currentController = "";
        continue;
      }
      const pathMatch = line.match(/^\s+path:\s*['"]?([^'"]+)['"]?/);
      if (pathMatch) {
        currentPath = pathMatch[1];
        continue;
      }
      const controllerMatch = line.match(/^\s+_(?:controller|form):\s*['"]?([^'"]+)['"]?/);
      if (controllerMatch) {
        currentController = controllerMatch[1];
      }
    }
    if (currentPath && currentController) {
      routes.push(this.createRouteBinding(currentPath, currentController, filePath, ctx));
    }
    return routes;
  }
  createRouteBinding(path, controller, filePath, ctx) {
    const parts = controller.split("::");
    const controllerClass = parts[0];
    const controllerMethod = parts[1] || "default";
    const symbol = controllerClass.split("\\").pop() || "Controller";
    let resolvedFile = filePath;
    const resolvedPath = ctx.resolveSymbolToFile(symbol);
    if (resolvedPath) {
      resolvedFile = resolvedPath;
    }
    return {
      framework: this.name,
      method: "ALL",
      path,
      handlerFile: resolvedFile,
      handlerSymbol: `${symbol}::${controllerMethod}`,
      metadata: {
        confidence: "inferred",
        routeType: "server"
      }
    };
  }
  async extractHooks(filePath, content, ctx) {
    if (!filePath.endsWith(".module")) {
      return [];
    }
    const hooks = [];
    const moduleName = basename(filePath, ".module");
    const functionRegex = new RegExp(`function\\s+(${moduleName})_([a-zA-Z0-9_]+)\\s*\\(`, "g");
    let match;
    while ((match = functionRegex.exec(content)) !== null) {
      const hookName = match[2];
      hooks.push({
        framework: this.name,
        hookName,
        handlerFile: filePath,
        handlerSymbol: `${moduleName}_${hookName}`,
        hookType: "hook"
      });
    }
    return hooks;
  }
}
export {
  DrupalDetector
};
