import { useQuery } from '@tanstack/react-query'

/**
 * Deployment mode (CR-20260607-001 rev.2 Q8).
 *
 * The backend exposes GET /api/v1/setup/mode WITHOUT auth so the top-bar
 * chip and the first-run wizard can adapt before the user logs in.
 */
export type DeploymentMode = 'desktop' | 'lab' | 'paas'

export interface ModeInfo {
  mode: DeploymentMode
  tenant_alias: string
  bootstrapped: boolean
}

const BASE = '/api/v1'

export async function fetchMode(): Promise<ModeInfo> {
  const res = await fetch(`${BASE}/setup/mode`)
  if (!res.ok) {
    // Older backends (pre-rev.2) have no /setup/mode — default to desktop
    // so the UI degrades gracefully instead of crashing.
    return { mode: 'desktop', tenant_alias: '', bootstrapped: false }
  }
  return res.json() as Promise<ModeInfo>
}

/**
 * React hook returning the current deployment mode. Cached for 5 min;
 * mode rarely changes within a session (it's a deploy-time decision).
 */
export function useMode() {
  return useQuery({
    queryKey: ['deployment-mode'],
    queryFn: fetchMode,
    staleTime: 5 * 60_000,
    // Never error the UI on a mode fetch — fall back to desktop.
    retry: false,
    placeholderData: { mode: 'desktop', tenant_alias: '', bootstrapped: false },
  })
}

/**
 * Per-mode display metadata for the top-bar chip and brand. Keeping this
 * as a single source of truth so the wording/color is consistent
 * everywhere (CR §10.3 / Q8).
 */
export const MODE_META: Record<
  DeploymentMode,
  { label: string; brand: string; chipClass: string; icon: string }
> = {
  desktop: {
    label: 'Desktop',
    brand: 'ResearchAgent Desktop',
    chipClass: 'bg-teal-100 text-teal-700 border-teal-200',
    icon: '🖥️',
  },
  lab: {
    label: 'Lab',
    brand: 'LambdAgent Lab',
    chipClass: 'bg-amber-100 text-amber-700 border-amber-200',
    icon: '👥',
  },
  paas: {
    label: 'PaaS',
    brand: 'LambdAgent PaaS',
    chipClass: 'bg-indigo-100 text-indigo-700 border-indigo-200',
    icon: '☁️',
  },
}
