/**
 * Settings hooks: tag → Paperclip company mappings.
 */

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "./client";

export type PaperclipCompany = {
  id: string;
  name: string;
  prefix: string;
};

export type TagMapping = {
  id: string;
  tag: string;
  tag_label: string;
  company_id: string;
  company_name: string;
  created_at: string;
};

export function usePaperclipCompanies() {
  return useQuery({
    queryKey: ["settings", "paperclip-companies"] as const,
    queryFn: ({ signal }) =>
      apiRequest<PaperclipCompany[]>("/api/settings/paperclip-companies", { signal }),
    staleTime: 60_000,
  });
}

export function useTagMappings() {
  return useQuery({
    queryKey: ["settings", "tag-mappings"] as const,
    queryFn: ({ signal }) =>
      apiRequest<TagMapping[]>("/api/settings/tag-mappings", { signal }),
    staleTime: 10_000,
  });
}

export function useAddTagMapping() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: { tag: string; tag_label: string; company_id: string; company_name: string }) =>
      apiRequest<TagMapping>("/api/settings/tag-mappings", { method: "POST", body }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings", "tag-mappings"] }),
  });
}

export function useDeleteTagMapping() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ ok: boolean }>(`/api/settings/tag-mappings/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings", "tag-mappings"] }),
  });
}

// ── MCP Settings ────────────────────────────────────────────────

export type EnvCategory =
  | "multimodal"
  | "rerank"
  | "halacha"
  | "credentials"
  | "connection"
  | "general";

export type EnvType = "bool" | "int" | "float" | "string";

export type McpEnvVar = {
  key: string;
  category: EnvCategory;
  type: EnvType;
  description: string;
  is_secret: boolean;
  is_editable: boolean;
  default: unknown;
  min: number | null;
  max: number | null;
  enum_values: string[] | null;
  coolify_value: string | null;
  container_value: string | null;
  drift: boolean;
  has_duplicates: boolean;
};

export type McpEnvResponse = {
  vars: McpEnvVar[];
  coolify_app_uuid: string;
  errors: string[];
};

export type McpTool = {
  name: string;
  description: string;
  params_schema: unknown;
  module: string;
  source_location: string;
};

export type McpRegistration = {
  client: string;
  server_name: string;
  command: string;
  args: string[];
  cwd: string;
  env_keys: string[];
  transport: string;
};

export function useMcpEnv() {
  return useQuery({
    queryKey: ["settings", "mcp-env"] as const,
    queryFn: ({ signal }) =>
      apiRequest<McpEnvResponse>("/api/settings/mcp/env", { signal }),
    staleTime: 5_000,
  });
}

export function useUpdateMcpEnv() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ key, value }: { key: string; value: unknown }) =>
      apiRequest<{
        ok: boolean;
        key: string;
        saved_value: string;
        requires_redeploy: boolean;
        message: string;
      }>(`/api/settings/mcp/env/${encodeURIComponent(key)}`, {
        method: "PATCH",
        body: { value },
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings", "mcp-env"] }),
  });
}

export function useMcpRedeploy() {
  return useMutation({
    mutationFn: () =>
      apiRequest<{ ok: boolean; deployment_uuid: string | null; message: string }>(
        "/api/settings/mcp/env/redeploy",
        { method: "POST" },
      ),
  });
}

export function useMcpTools() {
  return useQuery({
    queryKey: ["settings", "mcp-tools"] as const,
    queryFn: ({ signal }) =>
      apiRequest<{ tools: McpTool[]; count: number }>("/api/settings/mcp/tools", {
        signal,
      }),
    staleTime: 60_000,
  });
}

export function useMcpRegistrations() {
  return useQuery({
    queryKey: ["settings", "mcp-registrations"] as const,
    queryFn: ({ signal }) =>
      apiRequest<{
        registrations: McpRegistration[];
        error: string | null;
        message?: string;
      }>("/api/settings/mcp/registrations", { signal }),
    staleTime: 60_000,
  });
}

export type McpBlock = {
  id: string;
  index: number;
  title: string;
  gen_type: string;
  model: string;
  // The live generation knob (#204). Replaces the deprecated `temperature` —
  // Opus 4.7/4.8 have no temperature param. null for template ("script") blocks.
  effort: string | null;
  max_tokens: number | null;
  creac_role: string | null;
  jwm_purpose: string | null;
};

export function useMcpBlocks() {
  return useQuery({
    queryKey: ["settings", "mcp-blocks"] as const,
    queryFn: ({ signal }) =>
      apiRequest<{ blocks: McpBlock[]; count: number }>(
        "/api/settings/mcp/blocks",
        { signal },
      ),
    staleTime: 5 * 60_000, // 5 minutes — static reference data
  });
}
