import type { UiRoute } from "./model.js";

const knownProjectTabs = new Set([
  "overview",
  "vision",
  "goals",
  "plans",
  "work",
  "factory-runs",
  "reviews",
  "decisions",
  "ci",
  "delivery",
  "settings",
]);
const knownFactoryTabs = new Set(["overview", "tasks", "agent-runs", "timeline", "change-set"]);
const knownReviewTabs = new Set([
  "review",
  "files",
  "findings",
  "evidence",
  "provenance",
  "outcome",
]);

const value = (params: URLSearchParams, key: string): string | undefined => {
  const current = params.get(key);
  return current && current.length > 0 ? current : undefined;
};

export function resolveRoute(input: URL | string): UiRoute {
  const url = typeof input === "string" ? new URL(input, "http://awp.local") : input;
  const params = url.searchParams;
  const segments = url.pathname.split("/").filter(Boolean);

  if (segments[0] === "projects" && segments[1]) {
    if (segments[2] === "queue") {
      const task = value(params, "task");
      return {
        kind: "queue",
        id: segments[1],
        tab: value(params, "view") ?? "queue",
        state: value(params, "state") ?? "ready",
        ...(task ? { task } : {}),
      };
    }
    const tab = value(params, "tab") ?? "overview";
    return {
      kind: "project",
      id: segments[1],
      tab: knownProjectTabs.has(tab) ? tab : "overview",
      state: value(params, "state") ?? "ready",
    };
  }

  if (segments[0] === "factory-runs" && segments[1]) {
    const tab = value(params, "tab") ?? "overview";
    const task = value(params, "task");
    return {
      kind: "factory-run",
      id: segments[1],
      tab: knownFactoryTabs.has(tab) ? tab : "overview",
      state: value(params, "state") ?? "active",
      ...(task ? { task } : {}),
    };
  }

  if ((segments[0] === "changesets" || segments[0] === "reviews") && segments[1]) {
    const tab = value(params, "tab") ?? "review";
    const file = value(params, "file");
    const finding = value(params, "finding");
    return {
      kind: "review",
      id: segments[1],
      tab: knownReviewTabs.has(tab) ? tab : "review",
      state: value(params, "state") ?? "changes-requested",
      ...(file ? { file } : {}),
      ...(finding ? { finding } : {}),
    };
  }

  return { kind: "not-found" };
}

export function withQuery(path: string, params: Record<string, string | undefined>): string {
  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, current]) => {
    if (current) query.set(key, current);
  });
  const suffix = query.toString();
  return suffix.length > 0 ? `${path}?${suffix}` : path;
}
