import { timingSafeEqual } from 'node:crypto';
import type { SourceConfig } from '@pixeloffice/core';
import { StatusSchema } from '@pixeloffice/protocol';
import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
import type { Clock } from './clock.ts';
import type { ApplyOutcome, OfficeHost, TokenOutcome } from './host.ts';
import { filesToWire, parseAdminBody, ruIssues, type CheckResult } from './office-files.ts';
import { renderPreview, type SheetSource } from './preview.ts';
import type { PreviewStore } from './preview-store.ts';
import { officeReport } from './report.ts';
import type { Logger } from './logger.ts';
import { baseUrl, type Guides } from './guides.ts';
import { statusRows } from './status.ts';
import { EMOJI_LOGO_SIZES, EmojiImages, emojiLogo } from './emoji-logo.ts';

export type AdminOptions = { token: string; host: OfficeHost; previews: PreviewStore; sheets: SheetSource | null; clock: Clock; guides: Guides; log?: Logger };
// Тело /v1/admin/* (спека хостинга 5.5): свой лимит маршрута; глобальный bodyLimit 1 МБ не меняется.
export const ADMIN_BODY_LIMIT = 2_000_000;
const A = '/v1/admin';

// Сравнение за постоянное время: длины разные — сразу false (timingSafeEqual бросается на разной длине).
// Единственный путь сравнения admin-токена: его использует и доступ к /v1/guide/adapters в http.ts.
export const tokenMatches = (given: string, expected: string): boolean => {
  const g = Buffer.from(given);
  const e = Buffer.from(expected);
  return g.length === e.length && timingSafeEqual(g, e);
};

// Маршруты API администратора (спека хостинга 5.2). Доступ — отдельным плагином: хук действует ровно на эти
// маршруты уже после сопоставления пути, поэтому кодирование URL (/v1/%61dmin/…) токен не обходит; пути и cookie
// зрителя сюда не подходят. Отсутствие admin — 404 в общем крюке http.ts.
export function registerAdmin(app: FastifyInstance, a: AdminOptions): void {
  const { host } = a;
  void app.register(async (scope) => {
    scope.addHook('onRequest', async (req, reply) => {
      const given = /^bearer +(.+)$/i.exec(req.headers.authorization ?? '')?.[1];
      if (!(given && tokenMatches(given, a.token))) return reply.code(401).send({ error: 'unauthorized' });
    });
    scope.get(`${A}/office`, async () => {
      const cur = await host.office();
      return { version: cur.version, files: filesToWire(cur.files) };
    });
    scope.get(`${A}/versions`, async () => host.versions!.list());
    scope.get(`${A}/versions/:n`, async (req, reply) => {
      const raw = (req.params as { n: string }).n;
      // Только десятичные цифры: «1.0», «0x1», «1e0» Number превратил бы в 1 — у версии был бы не один адрес.
      const v = /^\d+$/.test(raw) ? host.versions!.read(Number(raw)) : null;
      if (!v) return reply.code(404).send({ error: 'not_found' });
      return { ...v.meta, files: filesToWire(v.files) };
    });
    scope.get(`${A}/status`, async () => statusRows(host.runtime, a.clock.now()));
    scope.get(`${A}/preview/:id/:file`, async (req, reply) => {
      const { id, file } = req.params as { id: string; file: string };
      const kind = file === 'plain.png' ? 'plain' : file === 'grid.png' ? 'grid' : null;
      const png = kind ? a.previews.get(id, kind) : null;
      if (!png) return reply.code(404).send({ error: 'not_found' });
      return reply.type('image/png').send(png);
    });
    // Ответ validate и apply (спека хостинга 5.4): отчёт и картинки — только у собранного набора.
    // extra — оговорки сервера после состоявшегося apply (код apply_partial) и признак unchanged.
    async function answer(check: CheckResult, version?: number, extra: { problems?: string[]; unchanged?: true } = {}) {
      if (!check.ok) return { ok: false, errors: check.errors, warnings: check.warnings, report: null, preview: null };
      let preview: { plain: string; grid: string } | null = null;
      if (a.sheets) {
        // Сбой картинки не должен прятать состоявшийся apply: версия и отчёт уходят клиенту, preview — null.
        try {
          const id = a.previews.put(await renderPreview(check.bundle, a.sheets));
          preview = { plain: `${A}/preview/${id}/plain.png`, grid: `${A}/preview/${id}/grid.png` };
        } catch (e) {
          a.log?.error(`предпросмотр не собран — ${(e as Error).message}`);
        }
      }
      let report: ReturnType<typeof officeReport> | null = null;
      try {
        report = officeReport(check.bundle);
      } catch (e) {
        a.log?.error(`отчёт не собран — ${(e as Error).message}`);
      }
      const server = (extra.problems ?? []).map((message) => ({ file: 'server', code: 'apply_partial', message }));
      return {
        ok: true,
        ...(version !== undefined ? { version } : {}),
        ...(extra.unchanged ? { unchanged: true } : {}),
        errors: [],
        warnings: [...check.warnings, ...server],
        report,
        preview,
      };
    }
    const body = (req: FastifyRequest, reply: FastifyReply) => {
      const r = parseAdminBody(req.body);
      if (!r.ok) {
        void reply.code(400).send({ error: 'invalid', message: r.message });
        return null;
      }
      return r.value;
    };
    // Ошибки Fastify до обработчика — в виде API и по-русски, как avatarErrorHandler в http.ts: английский текст
    // Fastify («Unexpected token…») в ответ не идёт. Битый или пустой JSON — 400, чужой Content-Type — 415, 413 — JSON.
    const errorHandler = (err: FastifyError, _req: FastifyRequest, reply: FastifyReply) => {
      const status = err.statusCode ?? 500;
      if (status === 413) return reply.code(413).send({ error: 'too_large', message: `тело запроса больше ${ADMIN_BODY_LIMIT} байт` });
      if (status === 415) return reply.code(415).send({ error: 'invalid', message: 'тело запроса — не JSON: нужен заголовок Content-Type: application/json' });
      if (err.code === 'FST_ERR_CTP_INVALID_JSON_BODY' || err.code === 'FST_ERR_CTP_EMPTY_JSON_BODY')
        return reply.code(400).send({ error: 'invalid', message: 'тело запроса — не JSON' });
      if (status < 500) return reply.code(400).send({ error: 'invalid', message: 'запрос не той формы' });
      a.log?.error(`admin: ${err.message}`);
      return reply.code(500).send({ error: 'internal', message: 'сбой сервера' });
    };
    // На весь плагин, включая wildcard ниже: битый JSON на неизвестный путь — тоже ответ API, а не тело Fastify.
    scope.setErrorHandler(errorHandler);
    const opts = { bodyLimit: ADMIN_BODY_LIMIT };

    // Токены источников и зрителей (спека admin-tokens 4): эффективный набор, выдача и отзыв на живом сервере,
    // без перезапуска и правки config.yaml. Токены не в URL — journald пишет каждый запрос (спека 2.6).
    const SourceBody = z.strictObject({
      source: z.string().min(1),
      owner: z.string().min(1).optional(),
      humans: z.boolean().optional(),
      ttlSec: z.union([z.number().int().positive(), z.partialRecord(StatusSchema, z.number().int().positive())]).optional(), // как в config.yaml
    });
    // Исключение из операции (сбой записи tokens.json на диск) — 500 с русским текстом, как safeOutcome у apply.
    const safeToken = async <T>(run: () => Promise<TokenOutcome<T>>): Promise<TokenOutcome<T>> => {
      try {
        return await run();
      } catch (e) {
        a.log?.error(`admin: токены — ${(e as Error).message}`);
        return { ok: false, status: 500, error: 'internal', message: 'сбой сервера' };
      }
    };
    const tokenError = (reply: FastifyReply, out: { ok: false; status: number; error: string; message: string }) =>
      reply.code(out.status).send({ error: out.error, message: out.message });
    scope.get(`${A}/tokens`, async () => host.effectiveTokens());
    scope.post(`${A}/tokens/sources`, opts, async (req, reply) => {
      const r = SourceBody.safeParse(req.body);
      if (!r.success) return reply.code(400).send({ error: 'invalid', message: ruIssues(r.error) });
      const out = await safeToken(() => host.addSource(r.data as { source: string; owner?: string; humans?: boolean; ttlSec?: SourceConfig['ttlSec'] }));
      if (!out.ok) return tokenError(reply, out);
      return out.value;
    });
    scope.delete(`${A}/tokens/sources/:source`, async (req, reply) => {
      const { source } = req.params as { source: string };
      const out = await safeToken(() => host.removeSource(source));
      if (!out.ok) return tokenError(reply, out);
      return reply.code(204).send();
    });
    // Тело выдачи токена зрителя (спека admin-tokens 4.4, адресных сообщений 2.2.3): пустое или { person } —
    // личный токен («я — человек person»); мусор — 400, как у соседнего POST sources.
    const ViewerIssueBody = z.strictObject({ person: z.string().min(1).optional() });
    scope.post(`${A}/tokens/viewers`, async (req, reply) => {
      const r = ViewerIssueBody.safeParse(req.body ?? {});
      if (!r.success) return reply.code(400).send({ error: 'invalid', message: ruIssues(r.error) });
      const out = await safeToken(() => host.addViewerToken(r.data.person));
      if (!out.ok) return tokenError(reply, out);
      return out.value; // { token, person? }
    });
    const ViewerBody = z.strictObject({ token: z.string().min(1) });
    scope.delete(`${A}/tokens/viewers`, async (req, reply) => {
      const r = ViewerBody.safeParse(req.body);
      if (!r.success) return reply.code(400).send({ error: 'invalid', message: ruIssues(r.error) });
      const out = await safeToken(() => host.revokeViewerToken(r.data.token));
      if (!out.ok) return tokenError(reply, out);
      return reply.code(204).send();
    });

    scope.post(`${A}/validate`, opts, async (req, reply) => {
      const b = body(req, reply);
      if (!b) return reply;
      const out = host.check(b.files, b);
      if (out.status === 'conflict') return reply.code(409).send({ error: 'version_conflict', current: out.current });
      return answer(out.check);
    });

    const applied = async (reply: FastifyReply, out: ApplyOutcome) => {
      if (out.status === 'conflict') return reply.code(409).send({ error: 'version_conflict', current: out.current });
      if (out.status === 'not_found') return reply.code(404).send({ error: 'not_found' });
      if (out.status === 'failed') return reply.code(500).send({ error: 'apply_failed', message: out.message });
      if (out.status === 'invalid') return answer(out.check);
      return answer(out.check, out.version, { ...(out.problems ? { problems: out.problems } : {}), ...(out.unchanged ? { unchanged: true as const } : {}) });
    };
    // Исключение из apply/rollback до фиксации (например, сбой записи версии на диск — состояние офиса не менялось;
    // после подмены runtime host.ts исключений не пропускает) — как исход
    // failed: клиенту русский текст, а не сырое английское исключение с путями.
    const safeOutcome = async (run: () => Promise<ApplyOutcome>): Promise<ApplyOutcome> => {
      try {
        return await run();
      } catch (e) {
        a.log?.error(`admin: apply/rollback — ${(e as Error).message}`);
        return { status: 'failed', message: 'версия не применена: сбой сервера, состояние офиса прежнее' };
      }
    };

    scope.post(`${A}/apply`, opts, async (req, reply) => {
      const b = body(req, reply);
      if (!b) return reply;
      return applied(reply, await safeOutcome(() => host.apply(b.files, b)));
    });

    const RollbackBody = z.strictObject({ version: z.number().int().min(1), comment: z.string().optional() });
    scope.post(`${A}/rollback`, opts, async (req, reply) => {
      const r = RollbackBody.safeParse(req.body);
      if (!r.success) return reply.code(400).send({ error: 'invalid', message: ruIssues(r.error) });
      // Длину comment проверяет checkFileSet, как у apply: неизвестная версия — 404 раньше неё.
      return applied(reply, await safeOutcome(() => host.rollback(r.data.version, r.data.comment)));
    });
    // Логотип из эмодзи (спека хостинга 5.7): готовый logo.png в base64 — ИИ кладёт его в набор файлов как есть.
    // Таблица эмодзи читается при первом запросе: офису без вывески она не нужна.
    let images: EmojiImages | null = null;
    const EmojiBody = z.strictObject({ emoji: z.string().min(1).max(32), size: z.union(EMOJI_LOGO_SIZES.map((n) => z.literal(n))).optional() });
    scope.post(`${A}/logo/emoji`, opts, async (req, reply) => {
      const r = EmojiBody.safeParse(req.body);
      if (!r.success) return reply.code(400).send({ error: 'invalid', message: ruIssues(r.error) });
      const size = r.data.size ?? 30;
      const png = emojiLogo((images ??= new EmojiImages()), r.data.emoji, size);
      if (!png) return reply.code(400).send({ error: 'unknown_emoji', message: `эмодзи «${r.data.emoji}» нет в наборе Noto — возьми другой` });
      return { png: png.toString('base64'), width: size, height: size };
    });
    // Инструкции (спека хостинга 8.3–8.5): markdown с адресом этого офиса; в скилле токена нет — его вставит ИИ сам.
    const md = (reply: FastifyReply, text: string) => reply.type('text/markdown; charset=utf-8').send(text);
    scope.get(`${A}/guide`, async (req, reply) => md(reply, a.guides.guide(baseUrl(req))));
    scope.get(`${A}/catalog`, async (_req, reply) => md(reply, a.guides.catalog()));
    scope.get(`${A}/skill`, async (req, reply) => md(reply, a.guides.skill(baseUrl(req))));
    // Прочие пути и методы под /v1/admin/ и сам /v1/admin — 404 JSON, а не тело 404 Fastify.
    scope.all(A, async (_req, reply) => reply.code(404).send({ error: 'not_found' }));
    scope.all(`${A}/*`, async (_req, reply) => reply.code(404).send({ error: 'not_found' }));
  });
}

