import { randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Clock } from './clock.ts';
import type { Logger } from './logger.ts';

// Файлы офиса, которые правит API администратора (спека хостинга 3.4): config.yaml сюда не входит никогда.
export type OfficeFileSet = { 'office.yaml': string; 'rules.yaml': string; 'people.yaml': string; 'logo.png': Buffer | null };
export const TEXT_FILES = ['office.yaml', 'rules.yaml', 'people.yaml'] as const;
export type VersionKind = 'initial' | 'apply' | 'rollback' | 'manual';
export type VersionMeta = { version: number; at: string; comment?: string; kind: VersionKind };
export const KEEP_VERSIONS = 50;

export const sameFileSet = (a: OfficeFileSet, b: OfficeFileSet): boolean =>
  TEXT_FILES.every((k) => a[k] === b[k]) && (a['logo.png'] === null ? b['logo.png'] === null : b['logo.png'] !== null && a['logo.png'].equals(b['logo.png']));

const NUM = /^\d+$/;

// История версий офиса (спека хостинга 6): <dataDir>/versions/<N>/ — файлы и meta.json. Версия пишется во временный
// каталог и переименовывается целиком: оборванная запись не оставляет полуверсии. Номер — последний выданный + 1
// (файл counter): номер удалённой версии (сбой apply) не выдаётся снова. Остатки оборванной записи (.tmp-*) удаляются
// при создании хранилища.
export class VersionStore {
  private readonly dir: string;
  private readonly clock: Clock;
  private readonly log: Logger | null;

  constructor(dataDir: string, clock: Clock, log?: Logger) {
    this.dir = join(dataDir, 'versions');
    this.clock = clock;
    this.log = log ?? null;
    mkdirSync(this.dir, { recursive: true });
    for (const n of readdirSync(this.dir)) if (n.startsWith('.tmp-')) rmSync(join(this.dir, n), { recursive: true, force: true });
  }

  list(): VersionMeta[] {
    return this.numbers()
      .sort((a, b) => b - a)
      .flatMap((n) => {
        const m = this.meta(n);
        return m ? [m] : [];
      });
  }

  latest(): VersionMeta | null {
    return this.list()[0] ?? null;
  }

  // Версия без одного из YAML (файл удалили руками) — битая: null, как несуществующая.
  read(n: number): { meta: VersionMeta; files: OfficeFileSet } | null {
    const meta = this.meta(n);
    if (!meta) return null;
    const d = join(this.dir, String(n));
    const text = (k: string) => readFileSync(join(d, k), 'utf8');
    const logo = join(d, 'logo.png');
    try {
      return {
        meta,
        files: { 'office.yaml': text('office.yaml'), 'rules.yaml': text('rules.yaml'), 'people.yaml': text('people.yaml'), 'logo.png': existsSync(logo) ? readFileSync(logo) : null },
      };
    } catch {
      return null;
    }
  }

  write(files: OfficeFileSet, kind: VersionKind, comment?: string): VersionMeta {
    const version = Math.max(this.counter(), ...this.numbers(), 0) + 1;
    const meta: VersionMeta = { version, at: new Date(this.clock.now()).toISOString(), ...(comment !== undefined ? { comment } : {}), kind };
    const tmp = join(this.dir, `.tmp-${version}-${randomBytes(4).toString('hex')}`);
    mkdirSync(tmp);
    for (const k of TEXT_FILES) writeFileSync(join(tmp, k), files[k]);
    if (files['logo.png']) writeFileSync(join(tmp, 'logo.png'), files['logo.png']);
    writeFileSync(join(tmp, 'meta.json'), JSON.stringify(meta));
    const counter = join(this.dir, 'counter');
    writeFileSync(`${counter}.tmp`, String(version));
    renameSync(`${counter}.tmp`, counter);
    renameSync(tmp, join(this.dir, String(version)));
    // Версия уже записана: сбой очистки старых её не отменяет — только в журнал, следующая запись очистит снова.
    try {
      this.prune();
    } catch (e) {
      this.log?.error(`история версий: старые версии не удалены — ${(e as Error).message}`);
    }
    return meta;
  }

  remove(n: number): void {
    rmSync(join(this.dir, String(n)), { recursive: true, force: true });
  }

  // Старт сервера с admin и начало GET office, apply и rollback (спека хостинга 6 п. 3): версий нет — initial; файлы
  // на диске не как в последней версии (оператор поправил их руками) — manual. Так GET office и baseVersion
  // соответствуют диску. Последняя версия битая (read — null) — тоже manual.
  ensureCurrent(files: OfficeFileSet): VersionMeta {
    const last = this.latest();
    if (!last) return this.write(files, 'initial');
    const cur = this.read(last.version);
    return cur && sameFileSet(cur.files, files) ? last : this.write(files, 'manual');
  }

  private numbers(): number[] {
    return readdirSync(this.dir).filter((n) => NUM.test(n)).map(Number);
  }

  private counter(): number {
    try {
      const n = Number(readFileSync(join(this.dir, 'counter'), 'utf8'));
      return Number.isInteger(n) && n > 0 ? n : 0;
    } catch {
      return 0;
    }
  }

  private meta(n: number): VersionMeta | null {
    try {
      return JSON.parse(readFileSync(join(this.dir, String(n), 'meta.json'), 'utf8')) as VersionMeta;
    } catch {
      return null;
    }
  }

  private prune(): void {
    for (const n of this.numbers().sort((a, b) => b - a).slice(KEEP_VERSIONS)) this.remove(n);
  }
}
