export const DEFAULT_WORKBENCH_PROJECT_ID = "prj_hwpod_workbench";
export const WORKBENCH_PROJECT_ID = DEFAULT_WORKBENCH_PROJECT_ID;
export const WORKBENCH_PROJECT_ID_STORAGE_KEY = "hwlab.workbench.projectId.v1";

const WORKBENCH_PROJECT_ID_PATTERN = /^prj_[A-Za-z0-9_.:-]{3,96}$/u;

export function normalizeWorkbenchProjectId(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const text = value.trim();
  return WORKBENCH_PROJECT_ID_PATTERN.test(text) ? text : null;
}

export function resolveInitialWorkbenchProjectId(): string {
  if (typeof window === "undefined") return DEFAULT_WORKBENCH_PROJECT_ID;
  const fromUrl = normalizeWorkbenchProjectId(new URLSearchParams(window.location.search).get("projectId"));
  const fromBootstrap = normalizeWorkbenchProjectId(window.HWLAB_CLOUD_WEB_WORKSPACE_BOOTSTRAP?.projectId);
  let fromStorage: string | null = null;
  try {
    fromStorage = normalizeWorkbenchProjectId(window.localStorage.getItem(WORKBENCH_PROJECT_ID_STORAGE_KEY));
  } catch {
    fromStorage = null;
  }
  return fromUrl ?? fromBootstrap ?? fromStorage ?? DEFAULT_WORKBENCH_PROJECT_ID;
}

export function rememberWorkbenchProjectId(projectId: string): void {
  const normalized = normalizeWorkbenchProjectId(projectId);
  if (!normalized || typeof window === "undefined") return;
  try {
    window.localStorage.setItem(WORKBENCH_PROJECT_ID_STORAGE_KEY, normalized);
  } catch {
    // localStorage may be unavailable in private / embedded contexts.
  }
}

export function workspaceProjectId(value: unknown, fallback = DEFAULT_WORKBENCH_PROJECT_ID): string {
  if (value && typeof value === "object") {
    const record = value as { projectId?: unknown; workspace?: { projectId?: unknown } | null; selectedConversation?: { projectId?: unknown } | null };
    return normalizeWorkbenchProjectId(record.projectId)
      ?? normalizeWorkbenchProjectId(record.workspace?.projectId)
      ?? normalizeWorkbenchProjectId(record.selectedConversation?.projectId)
      ?? fallback;
  }
  return fallback;
}
