import { readFileSync } from 'node:fs';
import path from 'node:path';

export type AutomationSupervisorStatus = 'starting' | 'online' | 'stopping' | 'stopped' | 'unmanaged';

export interface AutomationSupervisorState {
  port: number;
  status: AutomationSupervisorStatus;
  supervisorPid?: number;
  childPid?: number;
  updatedAt: string;
  reason?: string;
}

export interface AutomationControlConfig {
  port: string;
  runtimeDir: string;
  restartSignalFile: string;
  supervisorStateFile: string;
  portConfigError: string | null;
}

export interface SupervisorManagementStatus {
  managed: boolean;
  reason: string;
}

type ProcessProbe = (pid: number) => boolean;

function normalizePort(value: string | undefined) {
  const trimmed = value?.trim();
  return trimmed || undefined;
}

function defaultProcessProbe(pid: number) {
  try {
    process.kill(pid, 0);
    return true;
  } catch (error) {
    return error instanceof Error && 'code' in error && error.code === 'EPERM';
  }
}

export function resolveAutomationControlConfig(
  env: Pick<NodeJS.ProcessEnv, 'VITE_AUTOMATION_PORT' | 'AUTOMATION_PORT'>,
  projectRoot: string,
): AutomationControlConfig {
  const vitePort = normalizePort(env.VITE_AUTOMATION_PORT);
  const supervisorPort = normalizePort(env.AUTOMATION_PORT);
  const port = vitePort ?? supervisorPort ?? '3030';
  const runtimeDir = path.join(projectRoot, '.runtime', 'automation-control');
  const portConfigError = vitePort && supervisorPort && vitePort !== supervisorPort
    ? `VITE_AUTOMATION_PORT=${vitePort} 与 AUTOMATION_PORT=${supervisorPort} 不一致，无法安全控制自动化服务`
    : null;

  return {
    port,
    runtimeDir,
    restartSignalFile: path.join(runtimeDir, `restart-${port}.signal`),
    supervisorStateFile: path.join(runtimeDir, `state-${port}.json`),
    portConfigError,
  };
}

export function readAutomationSupervisorState(stateFile: string): AutomationSupervisorState | null {
  try {
    const raw = readFileSync(stateFile, 'utf8');
    const parsed = JSON.parse(raw) as Partial<AutomationSupervisorState>;
    if (typeof parsed.port !== 'number' || typeof parsed.status !== 'string' || typeof parsed.updatedAt !== 'string') {
      return null;
    }

    return parsed as AutomationSupervisorState;
  } catch {
    return null;
  }
}

export function getSupervisorManagementStatus(
  state: AutomationSupervisorState | null | undefined,
  options: { isProcessAlive?: ProcessProbe } = {},
): SupervisorManagementStatus {
  const isProcessAlive = options.isProcessAlive ?? defaultProcessProbe;

  if (!state) {
    return {
      managed: false,
      reason: '未发现当前端口的 automation API supervisor 状态',
    };
  }

  if (state.status === 'unmanaged') {
    return {
      managed: false,
      reason: `端口已有自动化 API，但不归当前 supervisor 管理${state.reason ? `：${state.reason}` : ''}`,
    };
  }

  if (typeof state.supervisorPid !== 'number') {
    return {
      managed: false,
      reason: '当前端口没有可确认的 automation API supervisor 进程',
    };
  }

  if (!isProcessAlive(state.supervisorPid)) {
    return {
      managed: false,
      reason: `automation API supervisor 进程 ${state.supervisorPid} 已不存在`,
    };
  }

  return {
    managed: true,
    reason: `automation API 由 supervisor ${state.supervisorPid} 管理`,
  };
}
