import {
  Database,
  Layers,
  Columns,
  RefreshCw,
  Wrench,
  StickyNote,
  Bookmark,
  BookmarkPlus,
  Activity,
  Shuffle,
  GitBranch,
  AlertTriangle,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";

export type ToolMeta = {
  icon: LucideIcon;
  label: string;
  preview: (parsed: Record<string, unknown>) => string | null;
};

const truncate = (s: unknown, n = 80): string | null => {
  if (typeof s !== "string") return null;
  return s.length > n ? `${s.slice(0, n)}…` : s;
};

export const TOOLS: Record<string, ToolMeta> = {
  list_databases: {
    icon: Database,
    label: "List databases",
    preview: () => null,
  },
  list_tables: {
    icon: Layers,
    label: "List tables",
    preview: (p) => (typeof p.database === "string" ? p.database : null),
  },
  get_columns: {
    icon: Columns,
    label: "Inspect columns",
    preview: (p) => (Array.isArray(p.tables) ? (p.tables as string[]).join(", ") : null),
  },
  switch_database: {
    icon: RefreshCw,
    label: "Switch database",
    preview: (p) => (typeof p.database === "string" ? p.database : null),
  },
  run_query: {
    icon: Wrench,
    label: "Run SQL",
    preview: (p) => truncate(p.sql),
  },
  remember: {
    icon: StickyNote,
    label: "Remember",
    preview: (p) => (typeof p.note === "string" ? p.note : null),
  },
  save_query: {
    icon: BookmarkPlus,
    label: "Save query",
    preview: (p) => (typeof p.name === "string" ? p.name : null),
  },
  find_queries: {
    icon: Bookmark,
    label: "Find saved queries",
    preview: (p) => (typeof p.text === "string" ? p.text : null),
  },
  profile_table: {
    icon: Activity,
    label: "Profile table",
    preview: (p) => (typeof p.table === "string" ? p.table : null),
  },
  sample_data: {
    icon: Shuffle,
    label: "Sample rows",
    preview: (p) => {
      const t = typeof p.table === "string" ? p.table : "";
      const limit = typeof p.limit === "number" ? p.limit : 50;
      return t ? `${t} (${limit})` : null;
    },
  },
  explain_query: {
    icon: GitBranch,
    label: "Explain query",
    preview: (p) => truncate(p.sql),
  },
  detect_skew: {
    icon: AlertTriangle,
    label: "Detect skew",
    preview: (p) => (typeof p.table === "string" ? p.table : null),
  },
};

export function getToolMeta(tool: string): ToolMeta {
  return (
    TOOLS[tool] ?? {
      icon: Wrench,
      label: tool,
      preview: () => null,
    }
  );
}

export function isQueryResultTool(tool: string): boolean {
  return tool === "run_query" || tool === "sample_data";
}
