export type AutomationServiceMonitorStatus =
  | 'checking'
  | 'online'
  | 'offline'
  | 'starting'
  | 'restart-sent'
  | 'unmanaged'
  | 'unsupported';

export interface AutomationServiceMonitorState {
  status: AutomationServiceMonitorStatus;
  canStart: boolean;
  message: string;
  source: 'vite-dev-server' | 'automation-api';
  checkedAt: string;
}

const DEV_STATUS_ENDPOINT = '/__automation-control/status';
const DEV_START_ENDPOINT = '/__automation-control/start';
const DEV_RESTART_ENDPOINT = '/__automation-control/restart';
const PRODUCTION_STATUS_ENDPOINT = '/api/state';

function toErrorMessage(error: unknown) {
  return error instanceof Error ? error.message : String(error);
}

function normalizeStatus(value: unknown): AutomationServiceMonitorStatus {
  if (
    value === 'online'
    || value === 'offline'
    || value === 'starting'
    || value === 'restart-sent'
    || value === 'unmanaged'
    || value === 'unsupported'
  ) {
    return value;
  }

  return 'offline';
}

function buildMonitorState(overrides: Partial<AutomationServiceMonitorState>): AutomationServiceMonitorState {
  return {
    status: 'checking',
    canStart: import.meta.env.DEV,
    message: '正在检测自动化服务',
    source: import.meta.env.DEV ? 'vite-dev-server' : 'automation-api',
    checkedAt: new Date().toISOString(),
    ...overrides,
  };
}

async function parseJsonBody(response: Response): Promise<Record<string, unknown>> {
  const body = await response.json().catch((): null => null);
  return body && typeof body === 'object' ? body as Record<string, unknown> : {};
}

function normalizeDevMonitorState(payload: Record<string, unknown>): AutomationServiceMonitorState {
  const status = normalizeStatus(payload.status);
  const canStart = typeof payload.canStart === 'boolean' ? payload.canStart : import.meta.env.DEV;
  const message = typeof payload.message === 'string' && payload.message.trim()
    ? payload.message.trim()
    : status === 'online'
      ? '自动化服务在线'
      : status === 'restart-sent'
        ? '已发送自动化服务重启请求'
      : status === 'starting'
        ? '正在启动自动化服务'
        : status === 'unmanaged'
          ? '当前自动化服务不归本地 supervisor 管理'
        : status === 'unsupported'
          ? '当前环境不支持前端拉起自动化服务'
          : '自动化服务离线';

  return buildMonitorState({
    status,
    canStart,
    message,
    source: 'vite-dev-server',
  });
}

export function getInitialAutomationServiceMonitorState(): AutomationServiceMonitorState {
  return buildMonitorState({ status: 'checking' });
}

export async function fetchAutomationServiceMonitorState(): Promise<AutomationServiceMonitorState> {
  if (import.meta.env.DEV) {
    try {
      const response = await fetch(DEV_STATUS_ENDPOINT, { cache: 'no-store' });
      const body = await parseJsonBody(response);

      if (!response.ok) {
        const message = typeof body.error === 'string'
          ? body.error
          : typeof body.message === 'string'
            ? body.message
            : `自动化服务状态检测失败: HTTP ${response.status}`;

        return buildMonitorState({
          status: 'offline',
          canStart: import.meta.env.DEV,
          message,
          source: 'vite-dev-server',
        });
      }

      return normalizeDevMonitorState(body);
    } catch (error) {
      return buildMonitorState({
        status: 'offline',
        canStart: import.meta.env.DEV,
        message: `自动化服务状态检测失败: ${toErrorMessage(error)}`,
        source: 'vite-dev-server',
      });
    }
  }

  try {
    const response = await fetch(PRODUCTION_STATUS_ENDPOINT, { cache: 'no-store' });
    if (!response.ok) {
      return buildMonitorState({
        status: 'offline',
        canStart: false,
        message: `自动化服务离线: HTTP ${response.status}`,
        source: 'automation-api',
      });
    }

    return buildMonitorState({
      status: 'online',
      canStart: false,
      message: '自动化服务在线',
      source: 'automation-api',
    });
  } catch (error) {
    return buildMonitorState({
      status: 'offline',
      canStart: false,
      message: `自动化服务离线: ${toErrorMessage(error)}`,
      source: 'automation-api',
    });
  }
}

export async function startAutomationServiceFromDevServer(): Promise<AutomationServiceMonitorState> {
  if (!import.meta.env.DEV) {
    throw new Error('仅开发环境支持从前端拉起自动化服务');
  }

  const response = await fetch(DEV_START_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const body = await parseJsonBody(response);

  if (!response.ok) {
    throw new Error(
      typeof body.error === 'string'
        ? body.error
        : typeof body.message === 'string'
          ? body.message
          : `拉起自动化服务失败: HTTP ${response.status}`,
    );
  }

  return normalizeDevMonitorState(body);
}

export async function restartAutomationServiceFromDevServer(): Promise<AutomationServiceMonitorState> {
  if (!import.meta.env.DEV) {
    throw new Error('仅开发环境支持从前端重启自动化服务');
  }

  const response = await fetch(DEV_RESTART_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const body = await parseJsonBody(response);

  if (!response.ok) {
    throw new Error(
      typeof body.error === 'string'
        ? body.error
        : typeof body.message === 'string'
          ? body.message
          : `重启自动化服务失败: HTTP ${response.status}`,
    );
  }

  return normalizeDevMonitorState(body);
}
