#! /usr/bin/env node
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import { outputDaemonStatus, io, pluginText } from '@axium/core/node';
import { _findPlugin, plugins } from '@axium/core/plugins';
import { program } from 'commander';
import { createServer } from 'node:http';
import { createInterface } from 'node:readline/promises';
import { styleText } from 'node:util';
import * as z from 'zod';
import $pkg from '../../package.json' with { type: 'json' };
import { config, resolveServerURL } from '../config.js';
import { prefix, setPrefix, setToken } from '../requests.js';
import { getCurrentSession, logout } from '../user.js';
import { loadConfig, saveConfig, updateCache } from './config.js';
const safe = z.stringbool().default(false).parse(process.env.SAFE?.toLowerCase()) || process.argv.includes('--safe');
const debug = z.stringbool().default(false).parse(process.env.DEBUG?.toLowerCase()) || process.argv.includes('--debug');
if (debug)
    io._setDebugOutput(true);
await loadConfig(safe);
process.on('SIGHUP', () => {
    io.info('Reloading configuration due to SIGHUP.');
    void loadConfig(safe);
});
var rl, axiumPlugin;
const env_1 = { stack: [], error: void 0, hasError: false };
try {
    rl = __addDisposableResource(env_1, createInterface({
        input: process.stdin,
        output: process.stdout,
    }), false);
    rl.on('SIGINT', () => io.exit('Aborted.', 7));
    program
        .version($pkg.version)
        .name('axium-client')
        .alias('axc')
        .description('Axium client CLI')
        .configureHelp({ showGlobalOptions: true })
        .option('--debug', 'override debug mode')
        .option('--no-debug', 'override debug mode')
        .option('--refresh-session', 'Force a refresh of session and user metadata from server')
        .option('--cache-only', 'Run entirely from local cache, even if it is expired.')
        .option('--safe', 'do not execute code from plugins');
    program.on('option:debug', () => io._setDebugOutput(true));
    program.hook('preAction', async (_, action) => {
        const opt = action.optsWithGlobals();
        if (!config.token)
            return;
        if (!opt.cacheOnly && action.name() != 'login')
            await updateCache(opt.refreshSession);
    });
    program
        .command('login')
        .description('Log in to your account on an Axium server')
        .argument('[server]', 'Axium server URL')
        .action(async (url) => {
        if (prefix[0] != '/')
            url ||= prefix;
        url ||= await rl.question('Axium server URL: ');
        url = resolveServerURL(url);
        setPrefix(url);
        const sessionReady = Promise.withResolvers();
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        const server = createServer(async (req, res) => {
            res.setHeader('access-control-allow-origin', '*');
            res.setHeader('access-control-allow-methods', '*');
            res.setHeader('access-control-allow-headers', '*');
            if (req.method == 'HEAD' || req.method == 'OPTIONS') {
                res.writeHead(200).end();
                return;
            }
            if (!req.headers['content-type']?.endsWith('/json')) {
                res.writeHead(415).end('Unexpected content type');
                return;
            }
            if (req.method !== 'POST') {
                res.writeHead(405).end('Unexpected request method');
                return;
            }
            const { promise: bodyReady, resolve, reject } = Promise.withResolvers();
            let body = '';
            req.on('data', chunk => (body += chunk.toString()));
            req.on('end', resolve);
            req.on('error', reject);
            try {
                await bodyReady;
                sessionReady.resolve(JSON.parse(body));
                res.writeHead(200).end();
            }
            catch (e) {
                res.statusCode = 500;
                res.end('Internal server error: ' + e.message);
                sessionReady.reject(e.message);
            }
        });
        const serverReady = Promise.withResolvers();
        server.listen(() => {
            const { port } = server.address();
            serverReady.resolve(port);
        });
        server.on('error', e => io.exit('Failed to start local callback server: ' + e.message, 5));
        const port = await serverReady.promise;
        const authURL = new URL('/login/client?port=' + port, url).href;
        console.log('Authenticate by visiting this URL in your browser: ' + styleText('underline', authURL));
        const { token } = await sessionReady.promise.catch(e => io.exit('Failed to obtain session: ' + e, 6));
        setToken(token);
        server.close();
        io.start('Verifying session');
        const session = await getCurrentSession().catch(e => io.exit(e.message, 6));
        io.done();
        io.debug('Session UUID: ' + session.id);
        console.log(`Welcome ${session.user.name}! Your session is valid until ${session.expires.toLocaleDateString()}.`);
        config.token = token;
        config.server = url;
        saveConfig();
        await updateCache(true);
    });
    program.command('logout').action(async () => {
        if (!config.token)
            io.exit('Not logged in.', 4);
        if (!config.cache)
            io.exit('No session data available.', 3);
        await logout(config.cache.session.userId, config.cache.session.id);
    });
    program.command('status').action(() => {
        if (!config.token)
            return console.log('Not logged in.');
        if (!config.cache)
            return console.log('No session data available.');
        console.log('Logged in to', new URL(prefix).host);
        console.log(styleText('whiteBright', 'Session ID:'), config.cache.session.id);
        const { user } = config.cache.session;
        console.log(styleText('whiteBright', 'User:'), user.name, `<${user.email}>`, styleText('dim', `(${user.id})`));
        outputDaemonStatus('axium-client');
    });
    program
        .command('run')
        .argument('[plugin]', 'The plugin to run')
        .action(async (name) => {
        if (name) {
            const plugin = _findPlugin(name);
            await plugin._client?.run();
            return;
        }
        for (const plugin of plugins.values())
            await plugin._client?.run();
    });
    axiumPlugin = program.command('plugin').alias('plugins').description('Manage plugins');
    axiumPlugin
        .command('list')
        .alias('ls')
        .description('List loaded plugins')
        .option('-l, --long', 'use the long listing format')
        .option('--no-versions', 'do not show plugin versions')
        .action((opt) => {
        if (!plugins.size) {
            console.log('No plugins loaded.');
            return;
        }
        if (!opt.long) {
            console.log(Array.from(plugins.keys()).join(', '));
            return;
        }
        console.log(styleText('whiteBright', plugins.size + ' plugin(s) loaded:'));
        for (const plugin of plugins.values()) {
            console.log(plugin.name, opt.versions ? plugin.version : '');
        }
    });
    axiumPlugin
        .command('info')
        .description('Get information about a plugin')
        .argument('<plugin>', 'the plugin to get information about')
        .action((search) => {
        const plugin = _findPlugin(search);
        for (const line of pluginText(plugin))
            console.log(line);
    });
    axiumPlugin
        .command('remove')
        .alias('rm')
        .description('Remove a plugin')
        .argument('<plugin>', 'the plugin to remove')
        .action((search) => {
        const plugin = _findPlugin(search);
        config.plugins = config.plugins.filter(p => p !== plugin.specifier);
        plugins.delete(plugin.name);
        saveConfig();
    });
    await program.parseAsync();
}
catch (e_1) {
    env_1.error = e_1;
    env_1.hasError = true;
}
finally {
    __disposeResources(env_1);
}
