"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const readline = __importStar(require("readline"));
// First-run wizard. Asks for hub name, API key, server URL, and any
// endpoints the operator wants to register up front. Writes the result to
// /etc/appmint-hub/config.json (or wherever the user points it).
//
// Run via:
//   npx hub-agent setup
//   sudo node dist/setup.js
//
// The API key is generated server-side; this wizard just asks the operator
// to paste it. See the on-screen instructions below for where to mint one.
async function main() {
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
    const ask = (q, def) => new Promise((resolve) => {
        rl.question(def ? `${q} [${def}]: ` : `${q}: `, (a) => resolve((a || def || '').trim()));
    });
    // Load any existing config so re-running the wizard pre-fills the prompts
    // with current values. Hit Enter to keep, type to change. No "skip if
    // config exists" gate any more — operator can always reconfigure.
    let existing = null;
    try {
        existing = require('./config').loadConfig();
    }
    catch {
        existing = null;
    }
    const isReconfigure = !!existing;
    console.log('appmint-hub setup wizard');
    console.log('-------------------------');
    if (isReconfigure) {
        console.log('Reconfiguring existing hub. Press Enter to keep each current value');
        console.log('(or type a new one to change). API key is shown masked.');
    }
    else {
        console.log('Run this AFTER you have minted an API key:');
        console.log('');
        console.log('  1. Open the Business Made app → Operations → Devices');
        console.log('  2. Switch to the Hubs tab → click "Add hub"');
        console.log('  3. Fill in name + display name + business location → Save');
        console.log('  4. Click "Edit" on the new hub → "Generate" under API key');
        console.log('  5. Click "Copy connection string" — fastest path; paste it below.');
        console.log('     (Or paste the API key alone and type the rest by hand.)');
    }
    console.log('');
    const advanced = process.argv.includes('--advanced');
    // Fast path — paste the connection string from the UI ("Copy connection string"
    // button on the API key block). Format: Server=...;OrgId=...;HubName=...;ApiKey=...
    // The wizard parses it and skips the per-field prompts. If the user just hits
    // enter we fall through to the per-field path.
    const connInput = (await ask('Paste connection string (or press Enter to type fields)')).trim();
    let orgId = '';
    let hubName = '';
    let apiKey = '';
    let serverUrlFromConn = null;
    if (connInput) {
        const parts = connInput.split(';').map(s => s.trim()).filter(Boolean);
        for (const p of parts) {
            const eq = p.indexOf('=');
            if (eq < 0)
                continue;
            const k = p.slice(0, eq).trim().toLowerCase();
            const v = p.slice(eq + 1).trim();
            if (k === 'server')
                serverUrlFromConn = v;
            else if (k === 'orgid')
                orgId = v;
            else if (k === 'hubname')
                hubName = v;
            else if (k === 'apikey')
                apiKey = v;
        }
        if (orgId && hubName && apiKey) {
            console.log(`  → org=${orgId}  hub=${hubName}  key=${apiKey.slice(0, 8)}…`);
        }
        else {
            console.log('  Connection string was incomplete — falling back to per-field prompts.');
        }
    }
    // Use existing values as defaults on reconfigure — Enter keeps, typed
    // value overrides. apiKey shown masked so the operator can confirm it
    // exists without leaking it on screen.
    if (!orgId)
        orgId = await ask('Org id (tenant slug)', existing?.orgId);
    if (!hubName)
        hubName = await ask('Hub name (must match the "name" you set in step 3)', existing?.hubName);
    if (!apiKey) {
        const masked = existing?.apiKey ? `${existing.apiKey.slice(0, 8)}…(keep)` : undefined;
        const entered = await ask('API key' + (masked ? ' (Enter to keep current)' : ''), masked);
        apiKey = entered === masked ? existing.apiKey : entered;
    }
    // Server URL precedence: connection-string paste > existing config >
    // production default. Pass --advanced to choose interactively.
    let serverUrl = serverUrlFromConn || existing?.serverUrl || 'wss://appengine.appmint.io';
    if (advanced) {
        console.log('');
        console.log('Server target (advanced):');
        console.log('  1) Production       wss://appengine.appmint.io');
        console.log('  2) Local            ws://localhost:3300');
        console.log('  3) LAN host         ws://<host-or-ip>:3300');
        console.log('  4) Custom URL       paste your own ws/wss URL');
        const choice = (await ask('Pick 1 / 2 / 3 / 4', '1')).trim();
        if (choice === '2') {
            serverUrl = 'ws://localhost:3300';
        }
        else if (choice === '3') {
            const host = (await ask('  Host or IP (e.g. 192.168.1.239)')).trim();
            const port = (await ask('  Port', '3300')).trim();
            serverUrl = `ws://${host}:${port}`;
        }
        else if (choice === '4') {
            const url = (await ask('  Full URL (e.g. wss://appengine.staging.example.com)')).trim();
            if (url)
                serverUrl = url;
        }
        console.log(`  → server: ${serverUrl}`);
    }
    // Endpoints are added remotely via the admin UI now (Operations →
    // Devices → Hubs → Diagnose → Add peripheral). Server pushes the new
    // endpoint over WS, agent persists + hot-reloads. No reason to ask
    // here. Existing endpoints are preserved on reconfigure.
    const endpoints = existing?.endpoints || [];
    const out = {
        hubName,
        apiKey,
        orgId,
        serverUrl,
        endpoints,
        heartbeatMs: existing?.heartbeatMs ?? 30000,
        reconnectMs: existing?.reconnectMs ?? 5000,
        logLevel: existing?.logLevel ?? 'info',
    };
    const target = process.argv.find((a) => a.startsWith('--out='))?.slice('--out='.length)
        || (process.getuid && process.getuid() === 0 ? '/etc/appmint-hub/config.json' : path.resolve(process.cwd(), 'config.json'));
    try {
        fs.mkdirSync(path.dirname(target), { recursive: true });
        fs.writeFileSync(target, JSON.stringify(out, null, 2) + '\n', { mode: 0o600 });
        console.log(`\nConfig written to ${target}`);
        console.log('Permissions set to 0600 (read-only for owner) since it contains the API key.');
        console.log('\nNext:');
        console.log('  systemctl enable --now appmint-hub');
        console.log('  journalctl -u appmint-hub -f');
    }
    catch (e) {
        console.error(`Failed to write ${target}:`, e?.message);
        process.exit(1);
    }
    rl.close();
}
main().catch((e) => {
    console.error('setup error:', e?.message || e);
    process.exit(1);
});
//# sourceMappingURL=setup.js.map