"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.doCloud = doCloud;
exports.doCommunityPacks = doCommunityPacks;
const utils_1 = require("../utils");
const cloud_connector_1 = require("../../../05-community/share/cloud-connector");
async function doCloud(args) {
    (0, utils_1.printHeader)('Cell Cloud');
    const sub = args[1] || 'status';
    // ─── WORKSPACE SWITCHER ────────────────────────────────────────────
    if (sub === 'connect') {
        const email = args[2];
        const password = args[3];
        if (!email || !password) {
            (0, utils_1.printWarning)('Usage: cell cloud connect <email> <password>');
            (0, utils_1.printDim)('  Workspace will be set to current directory');
            return;
        }
        try {
            const config = await (0, cloud_connector_1.cloudLogin)(email, password);
            (0, utils_1.printSuccess)(`Connected as ${config.email}  |  Workspace: ${process.cwd()}`);
            (0, utils_1.printDim)(`  Device: ${config.deviceId}  |  Cloud: ${config.cloudUrl}`);
            (0, utils_1.printDim)('  Run `cell cloud sync` to push your patterns');
        }
        catch (e) {
            (0, utils_1.printWarning)(`Connection failed: ${String(e).substring(0, 80)}`);
        }
        return;
    }
    if (sub === 'whoami') {
        const config = (0, cloud_connector_1.loadConfig)();
        if (!config) {
            (0, utils_1.printDim)('Not connected. Run cell cloud connect <email> <password>');
            return;
        }
        console.log(utils_1.C.bold('  Connected as:'));
        console.log(`    Email:    ${config.email}`);
        console.log(`    Device:   ${config.deviceId}`);
        console.log(`    Workspace: ${process.cwd()}`);
        console.log(`    Cloud:    ${config.cloudUrl}`);
        console.log(`    Synced:   ${config.lastSync || 'never'}`);
        return;
    }
    // ─── LOGIN ────────────────────────────────────────────────────────
    if (sub === 'login') {
        const email = args[2];
        const password = args[3];
        const cloudUrl = args[4];
        if (!email || !password) {
            (0, utils_1.printWarning)('Usage: cell cloud login <email> <password> [cloud-url]');
            (0, utils_1.printDim)('  Example: cell cloud login user@email.com mypassword');
            (0, utils_1.printDim)('  Cloud URL defaults to https://cell.fivo.live');
            return;
        }
        try {
            const config = await (0, cloud_connector_1.cloudLogin)(email, password, cloudUrl);
            (0, utils_1.printSuccess)(`Logged in as ${config.email}`);
            (0, utils_1.printDim)(`  Device ID: ${config.deviceId}`);
            (0, utils_1.printDim)(`  Cloud URL: ${config.cloudUrl}`);
            (0, utils_1.printDim)('  Run `cell cloud sync` to push your intelligence');
        }
        catch (e) {
            (0, utils_1.printWarning)(`Login failed: ${String(e).substring(0, 80)}`);
        }
        return;
    }
    // ─── LOGOUT ───────────────────────────────────────────────────────
    if (sub === 'logout') {
        const config = (0, cloud_connector_1.loadConfig)();
        if (!config) {
            (0, utils_1.printDim)('Not logged in.');
            return;
        }
        (0, cloud_connector_1.deleteConfig)();
        (0, utils_1.printSuccess)('Logged out. Config removed.');
        return;
    }
    // ─── STATUS ───────────────────────────────────────────────────────
    if (sub === 'status') {
        const config = (0, cloud_connector_1.loadConfig)();
        if (!config) {
            (0, utils_1.printDim)('Not logged in. Run `cell cloud login <email> <password>`');
            return;
        }
        console.log(utils_1.C.bold('  Cloud Status:'));
        console.log(`    Email: ${config.email}`);
        console.log(`    Device: ${config.deviceId}`);
        console.log(`    Cloud URL: ${config.cloudUrl}`);
        console.log(`    Last sync: ${config.lastSync || 'never'}`);
        console.log(`    Auto-sync: ${config.syncEnabled ? 'ON' : 'OFF'}`);
        try {
            const healthy = await (0, cloud_connector_1.cloudHealthCheck)(config);
            console.log(`    Server: ${healthy ? '✅ Online' : '❌ Unreachable'}`);
        }
        catch {
            console.log('    Server: ❌ Unreachable');
        }
        try {
            const status = await (0, cloud_connector_1.cloudStatus)(config);
            console.log(`    Connected: ${status.connected ? '✅ Yes' : '❌ No'}`);
        }
        catch { }
        return;
    }
    // ─── SYNC ─────────────────────────────────────────────────────────
    if (sub === 'sync') {
        const config = (0, cloud_connector_1.loadConfig)();
        if (!config) {
            (0, utils_1.printWarning)('Not logged in. Run `cell cloud login <email> <password>` first.');
            return;
        }
        const direction = args[2] || 'both';
        // Verify connection first
        const healthy = await (0, cloud_connector_1.cloudHealthCheck)(config);
        if (!healthy) {
            (0, utils_1.printWarning)('Cloud server unreachable. Check your connection or try later.');
            return;
        }
        let pushDone = false;
        let pullDone = false;
        // Push
        if (direction === 'push' || direction === 'both') {
            try {
                const result = await (0, cloud_connector_1.cloudPush)(config);
                if (result.pushed) {
                    (0, utils_1.printSuccess)('Intelligence pushed to cloud');
                    if (result.warnings.length > 0) {
                        (0, utils_1.printDim)(`  ${result.warnings.length} privacy warnings (non-blocking)`);
                    }
                    pushDone = true;
                }
                else {
                    (0, utils_1.printWarning)(`Push blocked — privacy issues:`);
                    for (const w of result.warnings) {
                        (0, utils_1.printDim)(`  ⚠ ${w}`);
                    }
                }
            }
            catch (e) {
                (0, utils_1.printWarning)(`Push failed: ${String(e).substring(0, 80)}`);
            }
        }
        // Pull
        if (direction === 'pull' || direction === 'both') {
            try {
                const { packs, count } = await (0, cloud_connector_1.cloudPull)(config);
                (0, utils_1.printSuccess)(`Pulled ${count} community packs`);
                if (count > 0) {
                    for (const p of packs.slice(0, 5)) {
                        const trust = p.trustScore >= 80 ? '🟢' : p.trustScore >= 60 ? '🟡' : '🔴';
                        console.log(`    ${trust} ${p.title} (${p.category}, trust: ${p.trustScore})`);
                    }
                    (0, utils_1.printDim)(`  Viewed with: cell community list`);
                }
                pullDone = true;
            }
            catch (e) {
                (0, utils_1.printWarning)(`Pull failed: ${String(e).substring(0, 80)}`);
            }
        }
        if (!pushDone && !pullDone) {
            (0, utils_1.printWarning)('Sync failed. Run `cell cloud status` to check connection.');
        }
        return;
    }
    // ─── AUTO-SYNC ────────────────────────────────────────────────────
    if (sub === 'auto') {
        const config = (0, cloud_connector_1.loadConfig)();
        if (!config) {
            (0, utils_1.printWarning)('Not logged in.');
            return;
        }
        const toggle = args[2] || 'on';
        config.syncEnabled = toggle !== 'off';
        (0, cloud_connector_1.saveConfig)(config);
        (0, utils_1.printSuccess)(`Auto-sync: ${config.syncEnabled ? 'ON' : 'OFF'}`);
        return;
    }
    // ─── DEFAULT: show status ─────────────────────────────────────────
    const config = (0, cloud_connector_1.loadConfig)();
    if (config) {
        console.log(`  Logged in as: ${config.email} (${config.deviceId})`);
        console.log(`  Last sync: ${config.lastSync || 'never'}`);
    }
    else {
        (0, utils_1.printDim)('  Not connected. Run `cell cloud login <email> <password>`');
    }
}
// ─── Community Packs (local) ─────────────────────────────────────────────────
function doCommunityPacks(args) {
    (0, utils_1.printHeader)('Cell Community Packs');
    const sub = args[1] || 'list';
    if (sub === 'list') {
        const packs = (0, cloud_connector_1.getLocalPacks)();
        if (packs.length === 0) {
            console.log('  No community packs downloaded yet.');
            (0, utils_1.printDim)('  Run `cell cloud sync` to pull packs from the community.');
            return;
        }
        console.log(utils_1.C.bold(`  ${packs.length} Community Packs:`));
        for (const p of packs) {
            const trust = p.trustScore >= 80 ? '🟢' : p.trustScore >= 60 ? '🟡' : '🔴';
            console.log(`    ${trust} ${p.title}`);
            (0, utils_1.printDim)(`       Category: ${p.category} | Trust: ${p.trustScore} | Downloads: ${p.downloadCount}`);
        }
        return;
    }
    if (sub === 'show') {
        const id = args[2];
        if (!id) {
            (0, utils_1.printWarning)('Usage: cell community show <pack-id>');
            return;
        }
        const pack = (0, cloud_connector_1.getPackById)(id);
        if (!pack) {
            (0, utils_1.printWarning)(`Pack "${id}" not found. Use 'cell community list' to see available packs.`);
            return;
        }
        console.log(utils_1.C.bold(`  ${pack.title}`));
        console.log(`  Category: ${pack.category}`);
        console.log(`  Trust: ${pack.trustScore}/100 | Downloads: ${pack.downloadCount}`);
        console.log(`  ${pack.description}`);
        console.log();
        if (pack.rules && pack.rules.length > 0) {
            console.log(utils_1.C.bold('  Rules:'));
            for (const r of pack.rules.slice(0, 10)) {
                console.log(`    • ${r.text} (${r.confidence}%)`);
            }
        }
        if (pack.signals && Object.keys(pack.signals).length > 0) {
            console.log(utils_1.C.bold('  Key Signals:'));
            for (const [k, v] of Object.entries(pack.signals).slice(0, 5)) {
                console.log(`    • ${k}: ${v}`);
            }
        }
        return;
    }
    if (sub === 'install') {
        (0, utils_1.printDim)('  Community packs auto-install when pulled via `cell cloud sync`.');
        (0, utils_1.printDim)('  To apply a pack, review its rules and add what fits your workflow.');
        return;
    }
    // Default: list
    const packs = (0, cloud_connector_1.getLocalPacks)();
    if (packs.length === 0) {
        console.log('  No community packs yet.');
        (0, utils_1.printDim)('  Run `cell cloud sync` to pull packs.');
    }
    else {
        console.log(`  ${packs.length} packs available. Run 'cell community list' for details.`);
    }
}
//# sourceMappingURL=cloud.js.map