import { AppDataSource, SystemConfig } from '../models/index.js';
import { logger } from '../utils/logger.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 {
  logger.info('[PythonServiceConfig] 清除缓存');
  cached = null;
}

export async function getPythonServiceBaseUrl(): Promise<string> {
  const now = Date.now();
  if (cached && cached.expiresAt > now) {
    logger.info(`[PythonServiceConfig] 使用缓存: ${cached.url}`);
    return cached.url;
  }

  let fromDb = '';
  let dbError: any = null;
  try {
    logger.info('[PythonServiceConfig] 从数据库读取配置');
    if (AppDataSource.isInitialized) {
      const repo = AppDataSource.getRepository(SystemConfig);
      const row = await repo.findOne({ where: { configKey: CONFIG_KEY } });
      fromDb = String(row?.configValue || '').trim();
      logger.info(`[PythonServiceConfig] 数据库查询结果: ${fromDb || '(空)'}`);
    } else {
      logger.warn('[PythonServiceConfig] 数据库未初始化');
    }
  } catch (error) {
    dbError = error;
    logger.error(`[PythonServiceConfig] 数据库查询失败: ${error}`);
    fromDb = '';
  }

  const url = fromDb || FALLBACK_PYTHON_SERVICE_URL;
  cached = { url, expiresAt: now + CACHE_TTL_MS };
  
  if (fromDb) {
    logger.info(`[PythonServiceConfig] 使用数据库配置: ${url}`);
  } else if (dbError) {
    logger.warn(`[PythonServiceConfig] 使用后备配置（数据库错误）: ${url}`);
  } else {
    logger.warn(`[PythonServiceConfig] 使用后备配置（数据库无记录）: ${url}`);
  }
  
  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);
  }
}

