import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, isAbsolute, join, relative, resolve } from 'node:path';
import { parse } from 'yaml';
import type { OfficeTexts } from '@pixeloffice/core';

export const expandHome = (p: string): string => (p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p);

// Путь из конфига: ~ раскрывается, относительный — от каталога конфига (решение 6).
export const resolveFrom = (baseDir: string, p: string): string => {
  const e = expandHome(p);
  return isAbsolute(e) ? e : resolve(baseDir, e);
};

export type OfficeFiles = { dir: string; configPath: string; officePath: string; rulesPath: string; catalogPath: string; peoplePath: string };

export function officeFiles(dir: string): OfficeFiles {
  const abs = resolve(dir);
  const configPath = existsSync(join(abs, 'config.yaml')) ? join(abs, 'config.yaml') : join(abs, 'config.example.yaml');
  let catalogRel = '../../catalog/limezu/catalog.yaml';
  try {
    const raw = parse(readFileSync(configPath, 'utf8')) as { catalog?: unknown } | null;
    if (typeof raw?.catalog === 'string') catalogRel = raw.catalog;
  } catch {
    // Ошибку чтения/синтаксиса конфига покажет loadOfficeBundle.
  }
  // Люди (спека хостинга 3.1): people.yaml рядом с конфигом. У запасного config.example.yaml (режим validate:maps)
  // нет своего people.yaml — берётся people.example.yaml: local и team держат людей вне git, как config.yaml.
  const example = join(abs, 'people.example.yaml');
  const peoplePath =
    basename(configPath) === 'config.example.yaml' && !existsSync(join(abs, 'people.yaml')) && existsSync(example) ? example : join(abs, 'people.yaml');
  return { dir: abs, configPath, officePath: join(abs, 'office.yaml'), rulesPath: join(abs, 'rules.yaml'), catalogPath: resolveFrom(abs, catalogRel), peoplePath };
}

export function readOfficeTexts(dir: string): { files: OfficeFiles; texts: OfficeTexts } {
  const files = officeFiles(dir);
  const read = (p: string) => {
    if (!existsSync(p)) throw new Error(`нет файла ${p}`);
    return readFileSync(p, 'utf8');
  };
  const rel = (p: string) => relative(process.cwd(), p);
  return {
    files,
    texts: {
      office: read(files.officePath),
      rules: read(files.rulesPath),
      config: read(files.configPath),
      catalog: read(files.catalogPath),
      people: existsSync(files.peoplePath) ? read(files.peoplePath) : undefined,
      files: { office: rel(files.officePath), rules: rel(files.rulesPath), config: rel(files.configPath), catalog: rel(files.catalogPath), people: rel(files.peoplePath) },
    },
  };
}
