import { AppDataSource, SystemConfig } from '../models/index.js';

const FALLBACK_PYTHON_SERVICE_URL =
  process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || process.env.PYTHON_API_URL || 'http://localhost:5005';

const CONFIG_KEY = 'python_publish_service_url';
const CACHE_TTL_MS = 30_000;

let cached: { url: string; expiresAt: number } | null = null;

export function invalidatePythonServiceBaseUrlCache(): void {
  cached = null;
}

export async function getPythonServiceBaseUrl(): Promise<string> {
  const now = Date.now();
  if (cached && cached.expiresAt > now) return cached.url;

  let fromDb = '';
  try {
    if (AppDataSource.isInitialized) {
      const repo = AppDataSource.getRepository(SystemConfig);
      const row = await repo.findOne({ where: { configKey: CONFIG_KEY } });
      fromDb = String(row?.configValue || '').trim();
    }
  } catch {
    fromDb = '';
  }

  const url = fromDb || FALLBACK_PYTHON_SERVICE_URL;
  cached = { url, expiresAt: now + CACHE_TTL_MS };
  return url;
}

export async function checkPythonServiceHealth(url?: string): Promise<{
  ok: boolean;
  status?: number;
  error?: string;
  data?: any;
}> {
  const baseUrl = (url || (await getPythonServiceBaseUrl())).replace(/\/$/, '');
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 5000);

  try {
    const res = await fetch(`${baseUrl}/health`, {
      method: 'GET',
      signal: controller.signal,
      headers: { 'Content-Type': 'application/json' },
    });
    const status = res.status;
    const text = await res.text();
    let data: any = null;
    try {
      data = text ? JSON.parse(text) : null;
    } catch {
      data = text || null;
    }
    return { ok: res.ok, status, data };
  } catch (e) {
    const error = e instanceof Error ? e.message : '请求失败';
    return { ok: false, error };
  } finally {
    clearTimeout(timeoutId);
  }
}

