import { vigthoriaHttpProxy } from '@/lib/tauri-bridge';

export interface VigthoriaService {
  id: string;
  name: string;
  url: string;
  authScope: string;
  apiVersion: string;
}

export interface ServiceHealth extends VigthoriaService {
  state: 'healthy' | 'protected' | 'unhealthy';
  status?: number;
  latencyMs: number;
  detail: string;
}

export const VIGTHORIA_SERVICE_CATALOG: VigthoriaService[] = [
  { id: 'coder', name: 'Coder account', url: 'https://coder.vigthoria.io/api/user/subscription', authScope: 'coder:account', apiVersion: 'v1' },
  { id: 'models', name: 'Model Router', url: 'https://api.vigthoria.io/health', authScope: 'public health', apiVersion: 'v1' },
  { id: 'hyperloop', name: 'Hyper-Loop', url: 'https://hyperloop.vigthoria.io/health', authScope: 'public health', apiVersion: '0.4' },
  { id: 'templates', name: 'Template Service', url: 'https://coder.vigthoria.io/api/template-service/stats', authScope: 'coder:templates', apiVersion: 'v1' },
  { id: 'community', name: 'Community repositories', url: 'https://community.vigthoria.io/api/repo/my-repos', authScope: 'community:repo', apiVersion: 'v1' },
  { id: 'v4', name: 'V4 Gateway', url: 'https://gateway.vigthoria.io/health', authScope: 'public health', apiVersion: 'v4' },
  { id: 'updates', name: 'Workbench updates', url: 'https://coder.vigthoria.io/releases/workbench-manifest.json', authScope: 'public release', apiVersion: 'manifest-v1' },
];

export async function probeService(service: VigthoriaService): Promise<ServiceHealth> {
  const started = performance.now();
  try {
    const response = await vigthoriaHttpProxy('GET', service.url, null, null);
    const latencyMs = Math.round(performance.now() - started);
    if (response.ok) {
      return { ...service, state: 'healthy', status: response.status, latencyMs, detail: 'Reachable' };
    }
    if (response.status === 401 || response.status === 403) {
      return { ...service, state: 'protected', status: response.status, latencyMs, detail: 'Reachable; authentication required' };
    }
    return { ...service, state: 'unhealthy', status: response.status, latencyMs, detail: `Unexpected HTTP ${response.status}` };
  } catch (error) {
    return {
      ...service,
      state: 'unhealthy',
      latencyMs: Math.round(performance.now() - started),
      detail: error instanceof Error ? error.message : String(error),
    };
  }
}
