import fs from "node:fs/promises";
import mariadb from "mariadb";

async function readEnv() {
  return Object.fromEntries(
    (await fs.readFile(".env", "utf8"))
      .split(/\r?\n/)
      .map((line) => line.trim())
      .filter((line) => line && !line.startsWith("#") && line.includes("="))
      .map((line) => {
        const index = line.indexOf("=");
        return [line.slice(0, index), line.slice(index + 1)];
      }),
  );
}

const env = await readEnv();
const connection = await mariadb.createConnection({
  host: env.DB_HOST || "127.0.0.1",
  port: Number(env.DB_PORT || 3306),
  user: env.DB_USER || "root",
  password: env.DB_PASSWORD || "",
});

try {
  const sql = await fs.readFile("sql/local-scrape-db.sql", "utf8");
  for (const statement of sql.split(/;\s*(?:\r?\n|$)/).map((item) => item.trim()).filter(Boolean)) {
    await connection.query(statement);
  }
  console.log("Local scrape database and schema are ready.");
} finally {
  await connection.end();
}
