console.log('[Oasis Mobile] Node.js backend starting...');

process.env.HOME = process.env.HOME || require('path').resolve(__dirname, '..', '..');
process.env.ssb_appname = process.env.ssb_appname || 'ssb';
process.env.OASIS_MOBILE = '1';
process.env.CHLORIDE_JS = '1';

const path = require('path');
const fs = require('fs');

const tmpDir = path.join(process.env.HOME, 'tmp');
try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {}
process.env.TMPDIR = tmpDir;
process.env.TMP = tmpDir;
process.env.TEMP = tmpDir;
try { require('os').tmpdir = () => tmpDir; } catch (e) {}

try {
    const dns = require('dns');
    const net = require('net');
    const servers = ['8.8.8.8', '1.1.1.1', '8.8.4.4'];
    try { dns.setServers(servers); } catch (e) {}
    try { if (dns.promises && dns.promises.setServers) dns.promises.setServers(servers); } catch (e) {}

    const localResolve = (hostname, family) => {
        if (hostname === 'localhost' || hostname === 'localhost.localdomain' || hostname === 'ip6-localhost') {
            return family === 6 ? { address: '::1', family: 6 } : { address: '127.0.0.1', family: 4 };
        }
        const ipv = net.isIP(hostname);
        if (ipv) return { address: hostname, family: ipv };
        return null;
    };

    const safeLookup = function (hostname, options, callback) {
        if (typeof options === 'function') { callback = options; options = {}; }
        options = options || {};
        const family = options.family === 6 ? 6 : 4;
        const direct = localResolve(hostname, family);
        if (direct) {
            return process.nextTick(() => options.all
                ? callback(null, [direct])
                : callback(null, direct.address, direct.family));
        }
        const resolver = family === 6 ? dns.resolve6 : dns.resolve4;
        resolver.call(dns, hostname, (err, addrs) => {
            if (err || !addrs || !addrs.length) return callback(err || new Error('ENOTFOUND ' + hostname));
            if (options.all) return callback(null, addrs.map((a) => ({ address: a, family })));
            return callback(null, addrs[0], family);
        });
    };

    dns.lookup = safeLookup;
    if (dns.promises) {
        dns.promises.lookup = (hostname, options) => new Promise((resolve, reject) => {
            safeLookup(hostname, options || {}, (err, address, family) => {
                if (err) return reject(err);
                if (options && options.all) return resolve(address);
                resolve({ address, family });
            });
        });
    }
} catch (e) {}

const backendPath = path.join(__dirname, 'src', 'backend', 'backend.js');

console.log('[Oasis] Launching Oasis Social Network Utopia...');
console.log('[Oasis] Backend path:', backendPath);
console.log('[Oasis] HOME:', process.env.HOME);

try {
    require(backendPath);
    console.log('[Oasis] Backend started on port 3000');
} catch (error) {
    console.error('[Oasis] Error starting backend:', error);
}
