import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

const cache = new Map<string, { data: any; timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

async function fetchWithCache(url: string, force = false) {
  if (!force && cache.has(url)) {
    const cached = cache.get(url)!;
    if (Date.now() - cached.timestamp < CACHE_TTL) {
      return cached.data;
    }
  }
  const { data } = await api.get(url);
  cache.set(url, { data, timestamp: Date.now() });
  return data;
}

export const getCapabilities = async (limit = 100, offset = 0) => {
  return fetchWithCache(`/capability?limit=${limit}&offset=${offset}`);
};

export const getRequirements = async (limit = 100, offset = 0) => {
  return fetchWithCache(`/requirement?limit=${limit}&offset=${offset}`);
};

export const getTools = async (limit = 100, offset = 0) => {
  return fetchWithCache(`/tool?limit=${limit}&offset=${offset}`);
};

export const getKnowledge = async (page = 1, pageSize = 100, filters: Record<string, string> = {}) => {
  const params = new URLSearchParams({ page: page.toString(), page_size: pageSize.toString() });
  for (const [key, val] of Object.entries(filters)) {
    if (val) params.append(key, val);
  }
  return fetchWithCache(`/knowledge?${params.toString()}`);
};

export const searchKnowledge = async (q: string, filters: Record<string, string> = {}) => {
  const params = new URLSearchParams({ q });
  for (const [key, val] of Object.entries(filters)) {
    if (val) params.append(key, val);
  }
  return fetchWithCache(`/knowledge/search?${params.toString()}`);
};

export const getTags = async () => {
  return fetchWithCache(`/knowledge/meta/tags`);
};

export default api;
