import { readdir, stat } from "node:fs/promises";
import { join, basename } from "node:path";
import { readGitState, type GitState } from "@/lib/git/scanner";

export interface ScannedProject extends GitState {
  name: string;
  path: string;
}

async function dirExists(p: string): Promise<boolean> {
  try {
    const s = await stat(p);
    return s.isDirectory();
  } catch {
    return false;
  }
}

export async function scanProjectsInDir(rootPath: string): Promise<ScannedProject[]> {
  if (!(await dirExists(rootPath))) return [];
  const entries = await readdir(rootPath, { withFileTypes: true });
  const results: ScannedProject[] = [];
  for (const e of entries) {
    if (!e.isDirectory()) continue;
    const full = join(rootPath, e.name);
    const isGit = await dirExists(join(full, ".git"));
    if (!isGit) continue;
    const state = await readGitState(full);
    results.push({ name: basename(full), path: full, ...state });
  }
  return results;
}
