import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchPets, petAssetUrl, type PetSettings, type PetSummary } from '../api';

const CODEX_DEFAULT_COLS = 8;
const CODEX_DEFAULT_ROWS = 9;

export interface ActivePet {
  pet: PetSummary | null;
  settings: PetSettings;
  spriteUrl: string | null;
  previewUrl: string | null;
  imageUrl: string | null;
  frameWidth: number | null;
  frameHeight: number | null;
  gridCols: number | null;
  gridRows: number | null;
}

export function useActivePet(
  workerId?: string | null,
  /**
   * Physical backend id behind a proxy worker (e.g. LiteLLM deployment).
   * When set, takes precedence over workerId for pet selection so each
   * backend can be visually distinct even though they share an AAO worker.
   * See docs/superpowers/specs/2026-05-18-multi-team-gpu-pool-and-node-status-design.md.
   */
  lastBackendId?: string | null,
): {
  data: ActivePet | null;
  isLoading: boolean;
} {
  const query = useQuery({
    queryKey: ['user-pets'],
    queryFn: fetchPets,
    staleTime: 30_000,
  });

  const data = useMemo<ActivePet | null>(() => {
    if (!query.data) return null;
    // Selection order per Phase A design:
    //   1. workerPets[backendId]  — most specific (proxy backend granularity)
    //   2. workerPets[workerId]   — worker-level mapping
    //   3. activePetId            — global default
    const workerPets = query.data.settings.workerPets ?? {};
    const backendMappedId = lastBackendId && workerPets[lastBackendId]
      ? workerPets[lastBackendId]
      : undefined;
    const workerMappedId = workerId && workerPets[workerId]
      ? workerPets[workerId]
      : undefined;
    const petId = backendMappedId ?? workerMappedId ?? query.data.settings.activePetId ?? null;
    const pet = petId ? query.data.pets.find(p => p.id === petId) ?? null : null;
    const spriteUrl = pet?.spriteFile ? petAssetUrl(pet.id, pet.spriteFile) : null;
    const previewUrl = pet?.previewFile ? petAssetUrl(pet.id, pet.previewFile) : null;
    const usingSprite = !previewUrl && !!spriteUrl;
    const hasExplicitFrame = usingSprite && pet?.frameWidth != null && pet?.frameHeight != null;
    const gridCols = usingSprite && !hasExplicitFrame ? pet?.gridCols ?? CODEX_DEFAULT_COLS : null;
    const gridRows = usingSprite && !hasExplicitFrame ? pet?.gridRows ?? CODEX_DEFAULT_ROWS : null;
    return {
      pet,
      settings: query.data.settings,
      spriteUrl,
      previewUrl,
      imageUrl: previewUrl ?? spriteUrl,
      frameWidth: hasExplicitFrame ? pet?.frameWidth ?? null : null,
      frameHeight: hasExplicitFrame ? pet?.frameHeight ?? null : null,
      gridCols,
      gridRows,
    };
  }, [query.data, workerId, lastBackendId]);

  return { data, isLoading: query.isLoading };
}
