/**
 * Switchboard layout version marker (WP-02). File truth under switchboard root.
 */

import { join } from "node:path";

import { AtomicFile } from "../atomic/AtomicFile.ts";
import { SwitchboardPaths } from "../paths/SwitchboardPaths.ts";

export const SWITCHBOARD_LAYOUT_VERSION = 1;

export interface SwitchboardVersionRecord {
  schema: "codeflowmu.switchboard-version/v1";
  layoutVersion: number;
  updatedAt: string;
  notes?: string;
}

export class SwitchboardVersionStore {
  readonly #paths: SwitchboardPaths;

  constructor(paths: SwitchboardPaths) {
    this.#paths = paths;
  }

  versionFile(): string {
    return join(this.#paths.root, "VERSION.json");
  }

  async read(): Promise<SwitchboardVersionRecord | null> {
    const path = this.versionFile();
    if (!(await AtomicFile.exists(path))) return null;
    return AtomicFile.readJson<SwitchboardVersionRecord>(path);
  }

  async write(
    patch?: Partial<Pick<SwitchboardVersionRecord, "notes" | "layoutVersion">>,
  ): Promise<SwitchboardVersionRecord> {
    const record: SwitchboardVersionRecord = {
      schema: "codeflowmu.switchboard-version/v1",
      layoutVersion: patch?.layoutVersion ?? SWITCHBOARD_LAYOUT_VERSION,
      updatedAt: new Date().toISOString(),
      ...(patch?.notes ? { notes: patch.notes } : {}),
    };
    await AtomicFile.writeJson(this.versionFile(), record);
    return record;
  }

  async ensureInitialized(): Promise<SwitchboardVersionRecord> {
    const existing = await this.read();
    if (existing) return existing;
    return this.write({ notes: "wp-02-init" });
  }
}
