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

export function readDatabaseUrl(stateDir) {
  return readStateValue(path.join(stateDir, "database_url"));
}

export function readDatabaseInfo(stateDir) {
  return parseDatabaseUrl(readDatabaseUrl(stateDir));
}

export function parseDatabaseUrl(databaseUrl) {
  if (!databaseUrl) return null;

  try {
    const parsed = new URL(databaseUrl);
    const port = Number(parsed.port || "5432");
    return {
      url: databaseUrl,
      host: parsed.hostname,
      port: Number.isInteger(port) && port > 0 ? port : 5432,
      database: parsed.pathname.replace(/^\//, ""),
      user: decodeURIComponent(parsed.username || ""),
      password: decodeURIComponent(parsed.password || ""),
    };
  } catch {
    return null;
  }
}

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

export function printStateDir(dir, indent) {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const filePath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      console.log(`${indent}${entry.name}/`);
      printStateDir(filePath, `${indent}  `);
      continue;
    }
    const value =
      entry.name === "password" ? "********" : fs.readFileSync(filePath, "utf8").trim();
    console.log(`${indent}${entry.name}: ${value}`);
  }
}
