import path from "path";
import { normalizePath, normalizeRoute } from "./shared.mjs";

export function inferPageRouteFromTestFile(filePath, nextAppRoot, serviceRoot) {
  const appRelativeSegments = extractRouteOwnerSegments(filePath, nextAppRoot, serviceRoot);
  if (!appRelativeSegments) return null;
  return normalizeRouteSegments(appRelativeSegments);
}

export function inferApiRoutesFromTestFile(filePath, nextAppRoot, serviceRoot) {
  const normalized = normalizePath(filePath);
  const appRootRelative = normalizePath(path.relative(serviceRoot, nextAppRoot));
  const appPrefix = appRootRelative === "." ? "" : `${appRootRelative}/`;
  const apiMarker = `${appPrefix}api/`;
  const markerIndex = normalized.indexOf(apiMarker);
  if (markerIndex === -1) return [];
  const rest = normalized.slice(markerIndex + apiMarker.length);
  const segments = rest.split("/");
  const testkitIndex = segments.indexOf("__testkit__");
  if (testkitIndex === -1) return [];
  return [normalizeRouteSegments(segments.slice(0, testkitIndex))];
}

export function inferOwnerDirectoryFromTestFile(filePath) {
  const normalized = normalizePath(filePath);
  const segments = normalized.split("/");
  const testkitIndex = segments.indexOf("__testkit__");
  if (testkitIndex <= 0) return null;
  return segments.slice(0, testkitIndex).join("/");
}

export function pathMatchesOwner(candidatePath, ownerDirectory) {
  const normalizedCandidate = normalizePath(candidatePath);
  const normalizedOwner = normalizePath(ownerDirectory);
  return normalizedCandidate === normalizedOwner || normalizedCandidate.startsWith(`${normalizedOwner}/`);
}

export function extractRouteOwnerSegments(filePath, nextAppRoot, serviceRoot) {
  const normalized = normalizePath(filePath);
  const appRootRelative = normalizePath(path.relative(serviceRoot, nextAppRoot));
  const appPrefix = appRootRelative === "." ? "" : `${appRootRelative}/`;
  if (!normalized.startsWith(appPrefix)) return null;
  const rest = normalized.slice(appPrefix.length);
  const segments = rest.split("/");
  const testkitIndex = segments.indexOf("__testkit__");
  if (testkitIndex === -1) return null;
  return segments.slice(0, testkitIndex);
}

export function routeFromAppFile(nextAppRoot, filePath) {
  const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(nextAppRoot, filePath);
  const relative = normalizePath(path.relative(nextAppRoot, absolutePath));
  const segments = relative.split("/");
  segments.pop();
  return normalizeRouteSegments(segments);
}

export function routeFromApiFile(nextAppRoot, filePath) {
  const appRelative = normalizePath(path.relative(nextAppRoot, path.dirname(filePath)));
  const segments = appRelative.split("/").filter(Boolean);
  if (segments[0] === "api") segments.shift();
  return normalizeRouteSegments(segments);
}

export function normalizeRouteSegments(segments) {
  const normalizedSegments = segments
    .filter(Boolean)
    .filter((segment) => !segment.startsWith("(") || !segment.endsWith(")"))
    .filter((segment) => !segment.startsWith("@"))
    .filter((segment) => segment !== "page" && segment !== "route");
  return normalizeRoute(`/${normalizedSegments.join("/")}`);
}

export function apiRouteLookupKey(method, route) {
  return `${method}:${route}`;
}

export function toApiRequestPath(route) {
  return normalizeRoute(`/api${route === "/" ? "" : route}`);
}

export function toSelectionType(type, framework) {
  if (framework === "playwright") return "pw";
  if (type === "integration") return "int";
  return type;
}
