/** * VillSim API Client * Handles all communication with the backend simulation server. */ // Auto-detect API base from current page location (same origin) function getApiBase() { // When served by the backend, use same origin if (typeof window !== 'undefined') { return window.location.origin; } // Fallback for development return 'http://localhost:8000'; } class SimulationAPI { constructor() { this.baseUrl = getApiBase(); this.connected = false; this.lastState = null; } async request(endpoint, options = {}) { const url = `${this.baseUrl}${endpoint}`; try { const response = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers, }, }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } this.connected = true; return await response.json(); } catch (error) { console.error(`API Error (${endpoint}):`, error.message); this.connected = false; throw error; } } // Health check async checkHealth() { try { const data = await this.request('/health'); this.connected = data.status === 'healthy'; return this.connected; } catch { this.connected = false; return false; } } // Get full simulation state async getState() { const data = await this.request('/api/state'); this.lastState = data; return data; } // Get all agents async getAgents() { return await this.request('/api/agents'); } // Get specific agent async getAgent(agentId) { return await this.request(`/api/agents/${agentId}`); } // Get market orders async getMarketOrders() { return await this.request('/api/market/orders'); } // Get market prices async getMarketPrices() { return await this.request('/api/market/prices'); } // Control: Initialize simulation async initialize(numAgents = 8, worldWidth = 20, worldHeight = 20) { return await this.request('/api/control/initialize', { method: 'POST', body: JSON.stringify({ num_agents: numAgents, world_width: worldWidth, world_height: worldHeight, }), }); } // Control: Advance one step async nextStep() { return await this.request('/api/control/next_step', { method: 'POST', }); } // Control: Set mode (manual/auto) async setMode(mode) { return await this.request('/api/control/mode', { method: 'POST', body: JSON.stringify({ mode }), }); } // Control: Get status async getStatus() { return await this.request('/api/control/status'); } // Config: Get configuration async getConfig() { return await this.request('/api/config'); } // Logs: Get recent logs async getLogs(limit = 10) { return await this.request(`/api/logs?limit=${limit}`); } // GOAP: Get debug info for all agents async getGOAPDebug() { return await this.request('/api/goap/debug'); } // GOAP: Get debug info for specific agent async getAgentGOAPDebug(agentId) { return await this.request(`/api/goap/debug/${agentId}`); } // Generic GET helper (for compatibility) async get(endpoint) { return await this.request(`/api${endpoint}`); } } // Export singleton instance export const api = new SimulationAPI(); export default api;