import path from "node:path";
import fg from "fast-glob";
import { APP_PATHS } from "../../lib/paths";
import type { CheckError, SyncCheckResult } from "../../lib/sync-check/shared";

/**
 * Screen sync check: validates that each screen doc in docs/screen/
 * has a corresponding page object in e2e/pages/.
 * Page objects without a screen doc are allowed (e.g., login).
 */
export async function runScreenPageSyncCheck(
  appRoot: string,
  cwd: string,
): Promise<SyncCheckResult> {
  const errors: CheckError[] = [];

  const screenDocPattern = `${appRoot}/${APP_PATHS.docs.screen}/*.md`;
  const screenDocs = await fg(screenDocPattern, { cwd });
  const docBasenames = new Set(screenDocs.map((p) => path.basename(p, ".md")));

  const pagePattern = `${appRoot}/${APP_PATHS.tests.e2e}/pages/**/*.ts`;
  const pageFiles = await fg(pagePattern, { cwd });
  const pageBasenames = new Set(pageFiles.map((p) => path.basename(p, ".ts")));

  for (const name of docBasenames) {
    if (!pageBasenames.has(name)) {
      errors.push({
        type: "missing-page-object",
        category: "screen",
        docPath: `${appRoot}/${APP_PATHS.docs.screen}/${name}.md`,
        expectedBasename: `${name}.ts`,
      });
    }
  }

  return { errors, filesChecked: screenDocs.length + pageFiles.length };
}
