/**
 * SwitchboardStartupRecovery — WP-14.
 * Crash recovery on Runtime/Shell start: orphans + health + optional repairs.
 */

import { SwitchboardPaths } from "../paths/SwitchboardPaths.js";
import {
  SwitchboardVersionStore,
  SWITCHBOARD_LAYOUT_VERSION,
} from "../store/SwitchboardVersionStore.js";
import {
  SwitchboardDiagnostics,
  type DiagnosticsReport,
} from "./SwitchboardDiagnostics.js";
import type { SwitchboardHealthReport } from "./SwitchboardHealth.js";

export interface StartupRecoveryResult {
  schema: "codeflowmu.switchboard-startup-recovery/v1";
  layoutVersion: number;
  initialized: boolean;
  health: SwitchboardHealthReport;
  diagnostics: DiagnosticsReport;
  productionActiveEnabled: false;
}

export interface StartupRecoveryOptions {
  paths: SwitchboardPaths;
  workerIds: string[];
  hostIds?: string[];
  projectRoot?: string;
  applyRepairs?: boolean;
  now?: () => Date;
}

export class SwitchboardStartupRecovery {
  readonly #diagnostics = new SwitchboardDiagnostics();

  async run(opts: StartupRecoveryOptions): Promise<StartupRecoveryResult> {
    const versions = new SwitchboardVersionStore(opts.paths);
    const before = await versions.read();
    const record = await versions.ensureInitialized();
    const diagnostics = await this.#diagnostics.diagnose({
      paths: opts.paths,
      workerIds: opts.workerIds,
      hostIds: opts.hostIds,
      projectRoot: opts.projectRoot,
      applyRepairs: opts.applyRepairs !== false,
      now: opts.now,
    });

    return {
      schema: "codeflowmu.switchboard-startup-recovery/v1",
      layoutVersion: record.layoutVersion || SWITCHBOARD_LAYOUT_VERSION,
      initialized: !before,
      health: diagnostics.health,
      diagnostics,
      productionActiveEnabled: false,
    };
  }
}
