import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";

const sourceRoot = join(process.cwd(), "src");

function listRuntimeFiles(directory: string): string[] {
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
    const target = join(directory, entry.name);
    if (entry.isDirectory()) return listRuntimeFiles(target);
    if (!/\.(ts|tsx)$/.test(entry.name) || /\.(test|e2e)\.(ts|tsx)$/.test(entry.name)) return [];
    return [target];
  });
}

function findMatches(directory: string, pattern: RegExp): string[] {
  return listRuntimeFiles(directory).flatMap((file) => {
    const source = readFileSync(file, "utf8");
    return pattern.test(source) ? [relative(sourceRoot, file)] : [];
  });
}

describe("frontend module boundaries", () => {
  it("uses public feature entry points for absolute feature imports", () => {
    expect(findMatches(sourceRoot, /@\/features\/(?:agent|workbench|map\/core)\//)).toEqual([]);
  });

  it("keeps shared independent from app, features, and mocks", () => {
    expect(findMatches(join(sourceRoot, "shared"), /@\/(?:app|features|mocks)\//)).toEqual([]);
  });

  it("keeps map core independent from Agent and workbench code", () => {
    expect(
      findMatches(
        join(sourceRoot, "features/map/core"),
        /@\/features\/(?:agent|workbench)(?:\/|["'])/
      )
    ).toEqual([]);
  });

  it("keeps Agent code independent from workbench code", () => {
    expect(
      findMatches(join(sourceRoot, "features/agent"), /@\/features\/workbench(?:\/|["'])/)
    ).toEqual([]);
  });

  it("does not restore Next.js client directives or the catch-all lib directory", () => {
    expect(findMatches(sourceRoot, /^["']use client["'];?/m)).toEqual([]);
    expect(existsSync(join(sourceRoot, "lib"))).toBe(false);
  });
});
