import fs from "fs";
import path from "path";

export function getLocalInfraDir(productDir) {
  return path.join(productDir, ".testkit", "_infra", "local-postgres");
}

export function getLocalLocksDir(productDir) {
  return path.join(getLocalInfraDir(productDir), "locks");
}

export function getLocalServiceCacheDir(productDir, serviceName) {
  return path.join(productDir, ".testkit", "_dbcache", serviceName);
}

export function hasRemainingLocalArtifacts(productDir, readStateValue) {
  const root = path.join(productDir, ".testkit");
  if (!fs.existsSync(root)) return false;

  let found = false;
  visitDirs(root, (dir) => {
    if (found) return;
    if (dir.includes(`${path.sep}.testkit${path.sep}_infra`)) return;
    if (readStateValue(path.join(dir, "database_backend")) === "local") {
      found = true;
    }
  });

  if (found) return true;

  const cacheRoot = path.join(productDir, ".testkit", "_dbcache");
  if (!fs.existsSync(cacheRoot)) return false;
  return fs.readdirSync(cacheRoot).some((entry) => {
    const entryPath = path.join(cacheRoot, entry);
    return fs.statSync(entryPath).isDirectory();
  });
}

export function visitDirs(root, visitor) {
  if (!fs.existsSync(root)) return;
  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
    if (!entry.isDirectory()) continue;
    const dir = path.join(root, entry.name);
    visitor(dir);
    visitDirs(dir, visitor);
  }
}

export function readStateValue(filePath) {
  if (!fs.existsSync(filePath)) return null;
  return fs.readFileSync(filePath, "utf8").trim();
}
