import fs from 'node:fs';
import os from 'node:os';
import net from 'node:net';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { 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 result = {};
  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);
    result[line.slice(0, index).trim()] = value;
  }
  return result;
}

const lines = [];
const add = (label, value) => lines.push(`${label}: ${value}`);
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 || 'installation';
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');

add('Tarih', new Date().toISOString());
add('OnlyCoin sürümü', fs.existsSync(path.join(rootDir, 'VERSION')) ? fs.readFileSync(path.join(rootDir, 'VERSION'), 'utf8').trim() : 'bilinmiyor');
add('Node.js', process.versions.node);
add('Platform', `${process.platform} ${process.arch}`);
add('İşletim sistemi', `${os.type()} ${os.release()}`);
add('Proje klasörü', rootDir);
add('Yapılandırma dosyası', envPath);
add('Ortam', environment);
add('Kurulum kilidi', fs.existsSync(path.join(dataDir, 'installed.json')) ? 'VAR' : 'YOK');

const required = [
  'server/src/server.js',
  'server/src/main.js',
  'server/src/installer.js',
  'server/src/db.js',
  'apps/installer/index.html',
  'apps/game/index.html',
  'apps/admin/index.html',
  'apps/website/index.html',
  'scripts/start.js'
];
for (const relative of required) add(`Dosya ${relative}`, fs.existsSync(path.join(rootDir, relative)) ? 'OK' : 'EKSİK');

try {
  fs.mkdirSync(dataDir, { recursive: true });
  const probe = path.join(dataDir, `.write-test-${process.pid}`);
  fs.writeFileSync(probe, 'ok');
  fs.rmSync(probe, { force: true });
  add('Data klasörü yazma testi', 'OK');
} catch (error) {
  add('Data klasörü yazma testi', `HATA - ${error.message}`);
}

try {
  await import('node:sqlite');
  add('node:sqlite', 'OK');
} catch (error) {
  add('node:sqlite', `HATA - ${error.message}`);
}

try {
  const health = inspectDatabaseFile(dbPath, { full: true });
  add('Veritabanı dosyası', dbPath);
  add('Veritabanı durumu', health.status.toUpperCase());
  add('Veritabanı boyutu', `${health.size || 0} bayt`);
  add('Veritabanı ayrıntısı', health.details || '-');
  const recoveryRoot = path.join(dataDir, 'recovery');
  const recoveryCount = fs.existsSync(recoveryRoot)
    ? fs.readdirSync(recoveryRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).length
    : 0;
  add('Kurtarma kopyası sayısı', recoveryCount);
} catch (error) {
  add('Veritabanı kontrolü', `HATA - ${error.message}`);
}

const port = Number.parseInt(process.env.PORT || fileEnv.PORT || '8787', 10) || 8787;
const portResult = await new Promise((resolve) => {
  const server = net.createServer();
  server.once('error', (error) => resolve(`KULLANILIYOR - ${error.code || error.message}`));
  server.once('listening', () => server.close(() => resolve('BOŞ')));
  server.listen(port, '127.0.0.1');
});
add(`127.0.0.1:${port}`, portResult);

const report = [
  'ONLYCOIN TANI RAPORU',
  '====================',
  ...lines,
  '',
  'Bu rapor parola, token, private key, seed phrase veya SMTP parolası içermez.'
].join('\r\n');

const reportPath = path.join(rootDir, 'ONLYCOIN-TANI-RAPORU.txt');
fs.writeFileSync(reportPath, report, 'utf8');
console.log(report);
console.log(`\nRapor oluşturuldu: ${reportPath}`);
