import { randomBytes } from "node:crypto";
import { spawnSync } from "node:child_process";
import { existsSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

const root = process.cwd();
const envPath = resolve(root, ".env");

function run(command: string, args: string[]) {
  const result = spawnSync(command, args, { cwd: root, stdio: "inherit", env: process.env, shell: false });
  if (result.status !== 0) process.exit(result.status ?? 1);
}

if (existsSync(envPath)) {
  console.error(".env already exists. It was not changed.");
  process.exit(1);
}

const postgresPassword = randomBytes(24).toString("base64url");
const jwtSecret = randomBytes(48).toString("base64url");
const encryptionKey = randomBytes(48).toString("base64url");

writeFileSync(envPath, [
  `POSTGRES_PASSWORD="${postgresPassword}"`,
  `DATABASE_URL="postgresql://aiwc:${postgresPassword}@localhost:5432/ai_web_command"`,
  `JWT_SECRET="${jwtSecret}"`,
  "APP_URL=\"http://localhost:3000\"",
  `CREDENTIAL_ENCRYPTION_KEY="${encryptionKey}"`,
  "REQUEST_SIGNATURE_MAX_AGE_SECONDS=\"300\"",
  "",
].join("\n"), { encoding: "utf8", mode: 0o600 });

console.log("Created a local-only .env with generated secrets.");
run("docker", ["compose", "up", "-d"]);
run(process.platform === "win32" ? "npx.cmd" : "npx", ["prisma", "migrate", "deploy"]);
run(process.platform === "win32" ? "npx.cmd" : "npx", ["tsx", "scripts/seed-demo.ts"]);
console.log("Local database is ready. Start the app with: npm run dev");
