import axios, { AxiosInstance } from 'axios';
import { readRuntimeInfo } from './runtime-info.js';

let client: AxiosInstance | null = null;

export function getHttpClient(): AxiosInstance {
  if (client) return client;
  const info = readRuntimeInfo();
  client = axios.create({
    baseURL: `http://127.0.0.1:${info.port}`,
    headers: info.controlSecret ? { 'x-neta-control-secret': info.controlSecret } : {},
    timeout: 60_000,
    // 不让 axios 在非 2xx 时抛异常，我们自己检查 code
    validateStatus: () => true,
  });
  return client;
}

export async function callDaemon<T = any>(path: string, body?: any): Promise<T> {
  const c = getHttpClient();
  const res = await c.post(path, body ?? {});
  if (res.data?.code !== 1000) {
    const msg = res.data?.error ?? res.data?.message ?? `HTTP ${res.status}: Unknown daemon error`;
    throw new Error(msg);
  }
  return res.data.data as T;
}

export async function callDaemonGet<T = any>(path: string): Promise<T> {
  const c = getHttpClient();
  const res = await c.get(path);
  if (res.data?.code !== 1000) {
    const msg = res.data?.error ?? res.data?.message ?? `HTTP ${res.status}: Unknown daemon error`;
    throw new Error(msg);
  }
  return res.data.data as T;
}
