import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'zod';
import { catalogGuide, itemComments, type Catalog } from '@pixeloffice/core';
import { EventsBodySchema } from '@pixeloffice/protocol';
import { previewLegend } from './preview.ts';

export type GuideTexts = { adminApi: string; officeFormat: string; wizard: string; adapters: string; skill: string };
// Тексты инструкций лежат в репозитории (спека хостинга 8): git-копия на хосте их содержит.
export const GUIDES_DIR = fileURLToPath(new URL('../../../docs/guides/', import.meta.url));

export function loadGuideTexts(dir = GUIDES_DIR): GuideTexts {
  const read = (f: string) => readFileSync(join(dir, f), 'utf8');
  return { adminApi: read('admin-api.md'), officeFormat: read('office-format.md'), wizard: read('wizard.md'), adapters: read('adapters.md'), skill: read('skill.md') };
}

// JSON Schema тела /v1/events (спека хостинга 8.6 п. 4) — из тех же схем zod, что проверяют события: не разойдётся.
export const eventsJsonSchema = (): string => JSON.stringify(z.toJSONSchema(EventsBodySchema, { io: 'input' }), null, 2);

const first = (v: string | string[] | undefined) => String(Array.isArray(v) ? v[0] : (v ?? '')).split(',')[0]!.trim();
// Адрес офиса для инструкций (спека хостинга 8): за reverse proxy — схема из X-Forwarded-Proto, хост — из Host.
export function baseUrl(req: { headers: Record<string, string | string[] | undefined> }): string {
  const proto = first(req.headers['x-forwarded-proto']).toLowerCase() === 'https' ? 'https' : 'http';
  return `${proto}://${first(req.headers['host'])}`;
}

const fill = (text: string, vars: Record<string, string>) => text.replace(/\{\{([A-Z_]+)\}\}/g, (m, k: string) => vars[k] ?? m);

export type Guides = { guide(base: string): string; catalog(): string; skill(base: string): string; adapters(base: string): string };

// Инструкции с подстановками (спека хостинга 8.1–8.3, 8.6): справочник каталога и схема считаются один раз.
export function buildGuides(t: GuideTexts, catalog: Catalog, catalogText: string): Guides {
  const cat = catalogGuide(catalog, itemComments(catalogText));
  const schema = eventsJsonSchema();
  const legend = previewLegend();
  return {
    guide: (base) => fill([t.adminApi, t.officeFormat, t.wizard, cat].join('\n\n'), { BASE_URL: base, PREVIEW_LEGEND: legend }),
    catalog: () => cat,
    skill: (base) => fill(t.skill, { BASE_URL: base }),
    adapters: (base) => fill(t.adapters, { BASE_URL: base, EVENTS_SCHEMA: schema }),
  };
}
