import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

// Спека 3: core и protocol не импортируют Node-API, DOM и PixiJS.
const ROOTS = ['../src/', '../../protocol/src/'].map((p) => fileURLToPath(new URL(p, import.meta.url)));
const FORBIDDEN_IMPORT =
  /from\s+['"](node:[^'"]+|fs|path|os|child_process|http|https|url|pixi\.js|pixi-viewport|fastify|@fastify\/[^'"]+|@pixeloffice\/(server|viewer)[^'"]*)['"]/;
const FORBIDDEN_GLOBAL = /\b(process\.|document\.|window\.|require\()/;

function tsFiles(dir: string): string[] {
  return readdirSync(dir).flatMap((name) => {
    const p = join(dir, name);
    if (statSync(p).isDirectory()) return tsFiles(p);
    return p.endsWith('.ts') ? [p] : [];
  });
}

describe('чистота core и protocol', () => {
  for (const root of ROOTS) {
    it(`нет Node-API, DOM и PixiJS в ${root}`, () => {
      const bad: string[] = [];
      for (const file of tsFiles(root)) {
        readFileSync(file, 'utf8')
          .split('\n')
          .forEach((line, i) => {
            if (FORBIDDEN_IMPORT.test(line) || FORBIDDEN_GLOBAL.test(line)) bad.push(`${file}:${i + 1}: ${line.trim()}`);
          });
      }
      expect(bad).toEqual([]);
    });
  }
});
