import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createVacuumBackup, inspectDatabaseFile } from '../server/src/database-health.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..');

function parseEnv(filePath) {
  if (!fs.existsSync(filePath)) return {};
  const output = {};
  for (const rawLine of fs.readFileSync(filePath, 'utf8').split(/\r?\n/)) {
    const line = rawLine.trim();
    if (!line || line.startsWith('#')) continue;
    const index = line.indexOf('=');
    if (index < 1) continue;
    let value = line.slice(index + 1).trim();
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
    output[line.slice(0, index).trim()] = value;
  }
  return output;
}

const envPath = path.resolve(process.env.ONLYCOIN_ENV_PATH || path.join(rootDir, '.env'));
const fileEnv = parseEnv(envPath);
const environment = process.env.NODE_ENV || fileEnv.NODE_ENV || 'production';
const dataDir = path.resolve(rootDir, process.env.DATA_DIR || fileEnv.DATA_DIR || './data');
const dbPath = path.join(dataDir, environment === 'test' ? 'onlycoin-test.db' : 'onlycoin.db');
const health = inspectDatabaseFile(dbPath, { full: true });
if (health.status !== 'healthy') {
  throw new Error(`Yedek alınamadı. Veritabanı durumu: ${health.status} - ${health.details || ''}`);
}
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
const destination = path.join(dataDir, 'backups', `onlycoin-${stamp}.db`);
const result = createVacuumBackup(dbPath, destination);
console.log(`Veritabanı yedeği oluşturuldu ve tam bütünlük kontrolüyle doğrulandı: ${result.destination}`);
