import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { existsSync } from "node:fs";
class RailsDetector {
  name = "rails";
  language = "ruby";
  filePattern = /routes\.rb$/;
  async detect(projectRoot, files) {
    const gemfiles = files.filter((f) => f === "Gemfile" || f.endsWith("/Gemfile"));
    if (gemfiles.length === 0) {
      gemfiles.push("Gemfile");
    }
    for (const file of gemfiles) {
      const gemfilePath = join(projectRoot, file);
      if (existsSync(gemfilePath)) {
        try {
          const content = await readFile(gemfilePath, "utf-8");
          if (content.includes("gem 'rails'") || content.includes('gem "rails"')) {
            return true;
          }
        } catch {
        }
      }
    }
    return false;
  }
  async extractRoutes(filePath, content, ctx) {
    const routes = [];
    if (!filePath.endsWith("routes.rb")) {
      return [];
    }
    const routeRegex = /\b(get|post|put|patch|delete)\s+['"]([^'"]+)['"]\s*,\s*to:\s*['"]([^'"]+)['"]/g;
    let match;
    while ((match = routeRegex.exec(content)) !== null) {
      const verb = match[1].toUpperCase();
      let pathVal = match[2];
      const controllerAction = match[3];
      pathVal = pathVal.replace(/:([a-zA-Z0-9_]+)/g, "{$1}");
      routes.push(this.createRouteBinding(verb, pathVal, controllerAction, filePath, ctx));
    }
    const resourcesRegex = /\bresources\s+:([a-zA-Z0-9_]+)/g;
    while ((match = resourcesRegex.exec(content)) !== null) {
      const resourceName = match[1];
      const controllerPrefix = resourceName.charAt(0).toUpperCase() + resourceName.slice(1);
      const controllerClass = `${controllerPrefix}Controller`;
      const crudEndpoints = [
        { verb: "GET", path: `/${resourceName}`, action: "index" },
        { verb: "GET", path: `/${resourceName}/new`, action: "new" },
        { verb: "POST", path: `/${resourceName}`, action: "create" },
        { verb: "GET", path: `/${resourceName}/{id}`, action: "show" },
        { verb: "GET", path: `/${resourceName}/{id}/edit`, action: "edit" },
        { verb: "PUT", path: `/${resourceName}/{id}`, action: "update" },
        { verb: "PATCH", path: `/${resourceName}/{id}`, action: "update" },
        { verb: "DELETE", path: `/${resourceName}/{id}`, action: "destroy" }
      ];
      for (const endpoint of crudEndpoints) {
        routes.push(this.createRouteBinding(endpoint.verb, endpoint.path, `${resourceName}#${endpoint.action}`, filePath, ctx));
      }
    }
    return routes;
  }
  createRouteBinding(verb, path, controllerAction, filePath, ctx) {
    const parts = controllerAction.split("#");
    const controller = parts[0];
    const action = parts[1] || "index";
    const controllerClassName = controller.charAt(0).toUpperCase() + controller.slice(1) + "Controller";
    let resolvedFile = filePath;
    const resolvedPath = ctx.resolveSymbolToFile(controllerClassName);
    if (resolvedPath) {
      resolvedFile = resolvedPath;
    }
    return {
      framework: this.name,
      method: verb,
      path,
      handlerFile: resolvedFile,
      handlerSymbol: `${controllerClassName}#${action}`,
      metadata: {
        confidence: "inferred",
        routeType: "server"
      }
    };
  }
}
export {
  RailsDetector
};
