import type { Character, DashboardData, Item, Monster, Resource, MapTile, BankData, AutomationConfig, AutomationRun, AutomationLog, AutomationStatus, GEOrder, GEHistoryEntry, PricePoint, ActiveGameEvent, HistoricalEvent, ActionLog, AnalyticsData, } from "./types"; const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000"; async function fetchApi(path: string): Promise { const response = await fetch(`${API_URL}${path}`); if (!response.ok) { throw new Error(`API error: ${response.status} ${response.statusText}`); } return response.json() as Promise; } async function postApi(path: string, body?: unknown): Promise { const response = await fetch(`${API_URL}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error( `API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}` ); } const contentType = response.headers.get("content-type"); if (contentType?.includes("application/json")) { return response.json() as Promise; } return undefined as T; } async function putApi(path: string, body?: unknown): Promise { const response = await fetch(`${API_URL}${path}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error( `API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}` ); } const contentType = response.headers.get("content-type"); if (contentType?.includes("application/json")) { return response.json() as Promise; } return undefined as T; } async function deleteApi(path: string): Promise { const response = await fetch(`${API_URL}${path}`, { method: "DELETE", }); if (!response.ok) { const text = await response.text().catch(() => ""); throw new Error( `API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}` ); } } // ---------- Auth API ---------- export interface AuthStatus { has_token: boolean; source: "env" | "user" | "none"; } export interface SetTokenResponse { success: boolean; source: string; account?: string | null; error?: string | null; } export function getAuthStatus(): Promise { return fetchApi("/api/auth/status"); } export async function setAuthToken(token: string): Promise { return postApi("/api/auth/token", { token }); } export async function clearAuthToken(): Promise { const response = await fetch(`${API_URL}/api/auth/token`, { method: "DELETE", }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json() as Promise; } // ---------- Characters API ---------- export function getCharacters(): Promise { return fetchApi("/api/characters"); } export function getCharacter(name: string): Promise { return fetchApi(`/api/characters/${encodeURIComponent(name)}`); } export function getDashboard(): Promise { return fetchApi("/api/dashboard"); } export function getItems(): Promise { return fetchApi("/api/game/items"); } export function getMonsters(): Promise { return fetchApi("/api/game/monsters"); } export function getResources(): Promise { return fetchApi("/api/game/resources"); } export function getMaps(): Promise { return fetchApi("/api/game/maps"); } export function getBank(): Promise { return fetchApi("/api/bank"); } // ---------- Automation API ---------- export function getAutomations(): Promise { return fetchApi("/api/automations"); } export function getAutomation( id: number ): Promise<{ config: AutomationConfig; runs: AutomationRun[] }> { return fetchApi<{ config: AutomationConfig; runs: AutomationRun[] }>( `/api/automations/${id}` ); } export function createAutomation(data: { name: string; character_name: string; strategy_type: string; config: Record; }): Promise { return postApi("/api/automations", data); } export function updateAutomation( id: number, data: Partial ): Promise { return putApi(`/api/automations/${id}`, data); } export function deleteAutomation(id: number): Promise { return deleteApi(`/api/automations/${id}`); } export function startAutomation(id: number): Promise { return postApi(`/api/automations/${id}/start`); } export function stopAutomation(id: number): Promise { return postApi(`/api/automations/${id}/stop`); } export function pauseAutomation(id: number): Promise { return postApi(`/api/automations/${id}/pause`); } export function resumeAutomation(id: number): Promise { return postApi(`/api/automations/${id}/resume`); } export function getAutomationStatuses(): Promise { return fetchApi("/api/automations/status/all"); } export function getAutomationStatus(id: number): Promise { return fetchApi(`/api/automations/${id}/status`); } export function getAutomationLogs( id: number, limit: number = 100 ): Promise { return fetchApi( `/api/automations/${id}/logs?limit=${limit}` ); } // ---------- Grand Exchange API ---------- export async function getExchangeOrders(): Promise { const res = await fetchApi<{ orders: GEOrder[] }>("/api/exchange/orders"); return res.orders; } export async function getMyOrders(): Promise { const res = await fetchApi<{ orders: GEOrder[] }>("/api/exchange/my-orders"); return res.orders; } export async function getExchangeHistory(): Promise { const res = await fetchApi<{ history: GEHistoryEntry[] }>("/api/exchange/history"); return res.history; } export async function getSellHistory(itemCode: string): Promise { const res = await fetchApi<{ history: GEHistoryEntry[] }>( `/api/exchange/sell-history/${encodeURIComponent(itemCode)}` ); return res.history; } export async function getPriceHistory(itemCode: string): Promise { const res = await fetchApi<{ entries: PricePoint[] }>( `/api/exchange/prices/${encodeURIComponent(itemCode)}` ); return res.entries; } // ---------- Events API ---------- export async function getEvents(): Promise { const res = await fetchApi<{ events: ActiveGameEvent[] }>("/api/events"); return res.events; } export async function getEventHistory(): Promise { const res = await fetchApi<{ events: HistoricalEvent[] }>("/api/events/history"); return res.events; } // ---------- Logs & Analytics API ---------- export async function getLogs(characterName?: string): Promise { const params = new URLSearchParams(); if (characterName) params.set("character", characterName); const qs = params.toString(); const data = await fetchApi(`/api/logs${qs ? `?${qs}` : ""}`); return Array.isArray(data) ? data : (data?.logs ?? []); } export function getAnalytics( characterName?: string, hours?: number ): Promise { const params = new URLSearchParams(); if (characterName) params.set("character", characterName); if (hours) params.set("hours", hours.toString()); const qs = params.toString(); return fetchApi(`/api/logs/analytics${qs ? `?${qs}` : ""}`); } // ---------- Character Actions API ---------- export function executeAction( characterName: string, action: string, params: Record ): Promise> { return postApi>( `/api/characters/${encodeURIComponent(characterName)}/action`, { action, params } ); }