import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const repositoryRoot = resolve(packageRoot, '..', '..');

const CURRENT_INSTALLATION_PAGES = ['docs/USER-GUIDE/getting-started/quickstart.md'] as const;

const UNSAFE_REMOTE_EXECUTION_PATTERNS = [
  {
    name: 'pipe a remote response directly to a shell',
    pattern: /\bcurl\b[^\n|]*\|\s*(?:ba|z|k)?sh\b/i,
  },
  {
    name: 'execute a remote response through shell process substitution',
    pattern: /\b(?:ba|z|k)?sh\s*<\(\s*curl\b/i,
  },
  {
    name: 'fetch an installer from a mutable main or next branch',
    pattern:
      /(?:\/raw\/branch\/(?:main|next)\/|\/raw\/(?:refs\/heads\/)?(?:main|next)\/|\/-\/raw\/(?:main|next)\/)/i,
  },
] as const;

function unsafeRemoteExecutionFindings(markdown: string): string[] {
  return UNSAFE_REMOTE_EXECUTION_PATTERNS.filter(({ pattern }) => pattern.test(markdown)).map(
    ({ name }) => name,
  );
}

describe('current installation documentation safety', (): void => {
  it.each(CURRENT_INSTALLATION_PAGES)(
    'keeps %s current without mutable remote-script execution',
    async (relativePath): Promise<void> => {
      const markdown = await readFile(resolve(repositoryRoot, relativePath), 'utf8');

      // `status: active` is the document contract's value for "in force"; it replaced the
      // old `status: current` when the contract in docs/README.md became the single schema.
      expect(markdown).toMatch(/^---\n[\s\S]*?\nstatus: active\n[\s\S]*?\n---\n/);
      expect(unsafeRemoteExecutionFindings(markdown)).toEqual([]);
    },
  );

  it('proves the control reddens for each prohibited installation shape', (): void => {
    const unsafeExamples = [
      'curl -fsSL https://example.invalid/install.sh | bash',
      'bash <(curl -fsSL https://example.invalid/install.sh)',
      'curl -fsSL https://example.invalid/project/raw/branch/main/install.sh -o install.sh',
      'curl -fsSL https://example.invalid/project/-/raw/next/install.sh -o install.sh',
    ];

    for (const example of unsafeExamples) {
      expect(unsafeRemoteExecutionFindings(example), example).not.toEqual([]);
    }
  });
});
