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

// Guards the AGPL-3.0 -> MIT relicense (openspec license-debt-mit). If any of
// these fail, AGPL-derived provenance has crept back in.
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../../..');

describe('license: MIT relicense guard', () => {
  it('LICENSE is MIT (no Affero/AGPL text)', () => {
    const license = readFileSync(resolve(ROOT, 'LICENSE'), 'utf8');
    expect(license).toMatch(/^MIT License/);
    expect(license).not.toMatch(/AFFERO|AGPL/i);
  });

  const PACKAGE_JSONS = [
    'package.json',
    'apps/server/package.json',
    'apps/web/package.json',
    'apps/coder/package.json',
    'apps/booterm/package.json',
  ];
  for (const rel of PACKAGE_JSONS) {
    it(`${rel} declares "license": "MIT"`, () => {
      const pkg = JSON.parse(readFileSync(resolve(ROOT, rel), 'utf8')) as { license?: string };
      expect(pkg.license).toBe('MIT');
    });
  }

  // The three files that were ported from Unsloth Studio (AGPL-3.0-only) and
  // cleared in this batch — they must carry no AGPL/Unsloth provenance.
  const FORMERLY_AGPL = [
    'apps/server/src/services/inference/tool-call-parser.ts',
    'apps/server/src/services/web/html-to-md.ts',
  ];
  for (const rel of FORMERLY_AGPL) {
    it(`${rel} carries no AGPL / Unsloth provenance`, () => {
      const src = readFileSync(resolve(ROOT, rel), 'utf8');
      expect(src).not.toMatch(/AGPL/);
      expect(src).not.toMatch(/SPDX-License-Identifier:\s*AGPL/);
      expect(src).not.toMatch(/Unsloth/i);
    });
  }
});
