import { PUBLIC_API_URL } from '$env/static/public';

const API_BASE = (PUBLIC_API_URL || 'http://localhost:8000') + '/api/v1';

async function request<T>(
	endpoint: string,
	options: RequestInit = {}
): Promise<T> {
	const response = await fetch(`${API_BASE}${endpoint}`, {
		...options,
		headers: {
			'Content-Type': 'application/json',
			...options.headers
		}
	});

	if (!response.ok) {
		throw new Error(`API Error: ${response.status} ${response.statusText}`);
	}

	return response.json();
}

export const api = {
	// Health
	health: () => request<{ status: string; version: string }>('/health'),

	// Inference Estimator
	estimate: {
		calculate: (data: {
			model: string;
			input_tokens_per_request: number;
			output_tokens_per_request: number;
			requests_per_day: number;
			days_per_month: number;
		}) =>
			request('/estimate/calculate', {
				method: 'POST',
				body: JSON.stringify(data)
			}),
		compare: (data: { models: string[]; input_tokens_per_request: number; output_tokens_per_request: number; requests_per_day: number }) =>
			request('/estimate/compare', {
				method: 'POST',
				body: JSON.stringify(data)
			}),
		models: () => request<{ models: Array<{ name: string; input: number; output: number }> }>('/estimate/models')
	},

	// Privacy Scanner
	privacy: {
		scanText: (text: string) =>
			request('/privacy/scan-text', {
				method: 'POST',
				body: JSON.stringify({ text })
			}),
		entityTypes: () => request('/privacy/entity-types')
	},

	// Data Audit
	audit: {
		analyze: (file: File) => {
			const formData = new FormData();
			formData.append('file', file);
			return fetch(`${API_BASE}/audit/analyze`, {
				method: 'POST',
				body: formData
			}).then((r) => r.json());
		}
	},

	// Drift Monitor
	drift: {
		history: () => request('/drift/history'),
		thresholds: (data: { psi_threshold: number; ks_threshold: number }) =>
			request('/drift/thresholds', {
				method: 'PUT',
				body: JSON.stringify(data)
			})
	},

	// Costs
	costs: {
		summary: () => request('/costs/summary'),
		providers: () => request('/costs/providers')
	},

	// Emergency
	emergency: {
		status: () => request('/emergency/status'),
		suspend: (system_id: string, reason: string) =>
			request('/emergency/suspend', {
				method: 'POST',
				body: JSON.stringify({ system_id, reason })
			}),
		resume: (system_id: string) =>
			request(`/emergency/resume/${system_id}`, { method: 'POST' })
	}
};
