import axios from 'axios';

const apiHost = typeof window !== 'undefined' && window.location.hostname ? window.location.hostname : '127.0.0.1';
const apiClient = axios.create({
  baseURL: `http://${apiHost}:8000`,
  headers: {
    'Content-Type': 'application/json',
  },
});



export interface Challenge {
  id: string;
  challenge_id: string;
  name: string;
  difficulty: string;
  language: string;
  subject?: string;
  description: string;
  requirements: string[];
  hints: string[];
}

export interface HandbookTopic {
  id: string;
  title: string;
  desc: string;
}

export interface HandbookCatalog {
  functions: HandbookTopic[];
  subjects: HandbookTopic[];
}

export const getChallenges = async (): Promise<Challenge[]> => {
  const response = await apiClient.get('/challenges');
  return response.data.challenges;
};

export const runCode = async (language: string, code: string, stdin: string = '') => {
  const response = await apiClient.post('/run', { language, code, stdin });
  return response.data;
};


export const lintCode = async (language: string, code: string) => {
  const response = await apiClient.post('/lint', { language, code });
  return response.data;
};

export const getGuidance = async (
  challengeId: string,
  language: string,
  code: string,
  question: string = ''
) => {
  const response = await apiClient.post('/guide', {
    challenge_id: challengeId,
    language,
    code,
    question,
  });
  return response.data;
};

export const getHandbookCatalog = async (language: string): Promise<HandbookCatalog> => {
  const response = await apiClient.get(`/handbook/catalog/${encodeURIComponent(language)}`);
  return response.data.catalog;
};

export const getHandbookTopics = async (language: string): Promise<HandbookTopic[]> => {
  const response = await apiClient.get(`/handbook/topics/${encodeURIComponent(language)}`);
  return response.data.topics;
};

export const getHandbookExample = async (
  language: string,
  topicId: string,
  topicTitle: string
) => {
  const response = await apiClient.post('/handbook/example', {
    language,
    topic_id: topicId,
    topic_title: topicTitle,
  });
  return response.data;
};
