"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 });
exports.initCloudWorker = initCloudWorker;
exports.cloudWorker = cloudWorker;
exports.pullCloudWorkerConfig = pullCloudWorkerConfig;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const KnowhowClient_1 = require("./services/KnowhowClient");
const login_1 = require("./login");
const config_1 = require("./config");
const services_1 = require("./services");
const fileSync_1 = require("./fileSync");
function buildWorkerConfigJson(config, files) {
    return {
        promptsDir: config.promptsDir,
        modules: config.modules,
        plugins: config.plugins,
        lintCommands: config.lintCommands,
        embedSources: config.embedSources,
        sources: config.sources,
        agents: config.agents,
        files,
        worker: {
            tunnel: {
                allowedPorts: config.worker?.tunnel?.allowedPorts ?? [],
            },
        },
    };
}
async function collectFilesToSync(projectName) {
    const filesToSync = [];
    const addIfExists = (localPath, remotePath) => {
        if (fs.existsSync(localPath)) {
            filesToSync.push({ localPath, remotePath });
        }
    };
    const addDirIfExists = (localPath, remotePath) => {
        if (fs.existsSync(localPath)) {
            filesToSync.push({ localPath: localPath + "/", remotePath: remotePath + "/", isDirectory: true });
        }
    };
    addIfExists(".knowhow/language.json", `${projectName}/.knowhow/language.json`);
    addIfExists(".knowhow/hashes.json", `${projectName}/.knowhow/hashes.json`);
    addDirIfExists(".knowhow/prompts", `${projectName}/.knowhow/prompts`);
    addDirIfExists(".knowhow/scripts", `${projectName}/.knowhow/scripts`);
    addDirIfExists(".knowhow/skills", `${projectName}/.knowhow/skills`);
    addDirIfExists(".knowhow/tasks", `${projectName}/.knowhow/tasks`);
    return filesToSync;
}
async function collectLanguageReferencedFiles(language, projectName) {
    const filesToSync = [];
    for (const term of Object.keys(language)) {
        const entry = language[term];
        if (!entry.sources)
            continue;
        for (const source of entry.sources) {
            if (source.kind !== "file" || !source.data)
                continue;
            for (const filePath of source.data) {
                const normalizedPath = filePath.replace(/^\.\//, "");
                if (normalizedPath === ".knowhow/knowhow.json")
                    continue;
                if (fs.existsSync(normalizedPath)) {
                    const basename = path.basename(normalizedPath);
                    const remotePath = `${projectName}/.knowhow/language/${basename}`;
                    filesToSync.push({ localPath: normalizedPath, remotePath, downloadLocalPath: normalizedPath });
                }
            }
        }
    }
    return filesToSync;
}
async function collectLanguageFilesIfConfigured(configFiles, projectName) {
    const syncingLanguage = configFiles.some((f) => !f.remotePath.endsWith("/") && f.remotePath.endsWith("language.json"));
    if (!syncingLanguage)
        return [];
    const language = await (0, config_1.getLanguageConfig)();
    return collectLanguageReferencedFiles(language, projectName);
}
async function initCloudWorker(options = {}) {
    const { dryRun = false } = options;
    const config = await (0, config_1.getConfig)();
    if (!config || Object.keys(config).length === 0) {
        console.error("❌ No knowhow config found. Please run 'knowhow init' first.");
        process.exit(1);
    }
    const projectName = path.basename(process.cwd());
    console.log(`📁 Project name: ${projectName}`);
    console.log("\n📂 Collecting files to sync...");
    const mainFiles = await collectFilesToSync(projectName);
    const languageFiles = await collectLanguageFilesIfConfigured(mainFiles, projectName);
    if (languageFiles.length === 0 && !mainFiles.some((f) => f.remotePath.endsWith("language.json"))) {
        console.log("   ℹ️  Skipping language-referenced files (language.json not found locally)");
    }
    const allFilesMap = new Map();
    for (const f of [...mainFiles, ...languageFiles]) {
        allFilesMap.set(f.remotePath, f);
    }
    const allFiles = Array.from(allFilesMap.values());
    console.log(`   Found ${allFiles.length} files to register`);
    const configFilesEntries = allFiles.map((f) => ({
        remotePath: f.remotePath,
        localPath: f.downloadLocalPath ?? f.localPath,
        direction: "download",
    }));
    console.log("\n💾 Updating config.files with sync entries...");
    if (!dryRun) {
        const existingFiles = config.files || [];
        const newRemotePaths = new Set(configFilesEntries.map((e) => e.remotePath));
        const preserved = existingFiles.filter((e) => !newRemotePaths.has(e.remotePath));
        config.files = [...preserved, ...configFilesEntries];
        await (0, config_1.updateConfig)(config);
        console.log(`   ✓ Updated config with ${config.files.length} file entries`);
    }
    else {
        console.log(`   [DRY RUN] Would update config with ${configFilesEntries.length} file entries`);
        for (const f of allFiles) {
            console.log(`   ${f.localPath} → ${f.remotePath}`);
        }
    }
}
async function cloudWorker(options) {
    const { create = false, push, name, apiUrl = KnowhowClient_1.KNOWHOW_API_URL, dryRun = false, } = options;
    if (!create && !push) {
        console.error("❌ Please specify --create or --push <uid>");
        process.exit(1);
    }
    const jwt = await (0, login_1.loadJwt)();
    if (!jwt) {
        console.error("❌ No JWT token found. Please run 'knowhow login' first.");
        process.exit(1);
    }
    const config = await (0, config_1.getConfig)();
    if (!config || Object.keys(config).length === 0) {
        console.error("❌ No knowhow config found. Please run 'knowhow init' first.");
        process.exit(1);
    }
    const projectName = path.basename(process.cwd());
    console.log(`📁 Project name: ${projectName}`);
    const client = new KnowhowClient_1.KnowhowSimpleClient(apiUrl, jwt);
    const { AwsS3 } = (0, services_1.services)();
    const configFiles = config.files || [];
    if (configFiles.length === 0) {
        console.warn("⚠️  No files configured. Run 'knowhow cloudworker --init' first to set up file sync entries.");
    }
    const languageFiles = await collectLanguageFilesIfConfigured(configFiles, projectName);
    if (languageFiles.length > 0) {
        console.log(`   + ${languageFiles.length} language-referenced file(s) to sync`);
    }
    const allFilesMap = new Map();
    for (const f of configFiles) {
        allFilesMap.set(f.remotePath, f);
    }
    for (const f of languageFiles) {
        const entry = { remotePath: f.remotePath, localPath: f.downloadLocalPath ?? f.localPath };
        allFilesMap.set(f.remotePath, entry);
    }
    const allFiles = Array.from(allFilesMap.values());
    if (languageFiles.length > 0 && !dryRun) {
        config.files = allFiles.map((f) => ({ ...f, direction: "download" }));
        await (0, config_1.updateConfig)(config);
    }
    const workerConfigJson = buildWorkerConfigJson(config, allFiles.map((f) => ({ ...f, direction: "download" })));
    console.log(`\n🚀 Uploading ${allFiles.length} configured files...`);
    let successCount = 0;
    let failCount = 0;
    for (const mount of allFiles) {
        const { remotePath, localPath } = mount;
        try {
            if (remotePath.endsWith("/") || localPath.endsWith("/")) {
                const count = await (0, fileSync_1.uploadDirectory)(client, AwsS3, remotePath, localPath, dryRun);
                successCount += count;
            }
            else {
                await (0, fileSync_1.uploadFile)(client, AwsS3, remotePath, localPath, dryRun);
                successCount++;
            }
        }
        catch (error) {
            console.error(`  ❌ Failed to upload ${localPath}: ${error.message}`);
            failCount++;
        }
    }
    console.log(`\n   ✓ Upload complete: ${successCount} succeeded, ${failCount} failed`);
    if (create) {
        const workerName = name || `${projectName}-worker`;
        console.log(`\n🌩️  Creating cloud worker "${workerName}"...`);
        if (dryRun) {
            console.log(`   [DRY RUN] Would create cloud worker with name: ${workerName}`);
            console.log(`   [DRY RUN] workerConfigJson:`, JSON.stringify(workerConfigJson, null, 2));
        }
        else {
            const result = await client.createCloudWorker({
                name: workerName,
                workerConfigJson,
            });
            const createdWorker = result.data;
            console.log(`   ✓ Cloud worker created!`);
            console.log(`   ID: ${createdWorker.id}`);
            console.log(`   Name: ${createdWorker.name}`);
            console.log(`\n💡 To push updates later, run:`);
            console.log(`   knowhow cloudworker --push ${createdWorker.id}`);
        }
    }
    else if (push) {
        console.log(`\n🌩️  Updating cloud worker "${push}"...`);
        if (dryRun) {
            console.log(`   [DRY RUN] Would update cloud worker ${push}`);
            console.log(`   [DRY RUN] workerConfigJson:`, JSON.stringify(workerConfigJson, null, 2));
        }
        else {
            await client.updateCloudWorker(push, { workerConfigJson });
            console.log(`   ✓ Cloud worker updated!`);
        }
    }
    if (failCount > 0) {
        console.warn(`\n⚠️  ${failCount} file(s) failed to upload.`);
    }
    else {
        console.log(`\n✅ Cloud worker sync complete!`);
    }
}
async function pullCloudWorkerConfig(options) {
    const { id, apiUrl = KnowhowClient_1.KNOWHOW_API_URL } = options;
    const jwt = await (0, login_1.loadJwt)();
    if (!jwt) {
        console.error("❌ No JWT token found. Please run 'knowhow login' first.");
        process.exit(1);
    }
    const client = new KnowhowClient_1.KnowhowSimpleClient(apiUrl, jwt);
    console.log(`🔄 Pulling config for cloud worker ${id}...`);
    const resp = await client.getCloudWorker(id);
    const remoteWorker = resp.data;
    if (!remoteWorker) {
        console.error(`❌ Cloud worker ${id} not found.`);
        process.exit(1);
    }
    const remoteConfig = (remoteWorker.workerConfigJson ?? {});
    const localConfig = await (0, config_1.getConfig)();
    if (remoteConfig.mcps !== undefined) {
        localConfig.mcps = remoteConfig.mcps;
    }
    if (remoteConfig.modules !== undefined) {
        localConfig.modules = remoteConfig.modules;
    }
    if (remoteConfig.plugins !== undefined) {
        localConfig.plugins = remoteConfig.plugins;
    }
    if (remoteConfig.agents !== undefined) {
        localConfig.agents = remoteConfig.agents;
    }
    await (0, config_1.updateConfig)(localConfig);
    const mcpCount = remoteConfig.mcps?.length ?? 0;
    console.log(`✅ Config pulled! ${mcpCount} MCP(s) now configured locally.`);
    console.log(`   Run 'knowhow worker' or trigger reloadConfig to apply changes.`);
    return { mcps: remoteConfig.mcps, modules: remoteConfig.modules };
}
//# sourceMappingURL=cloudWorker.js.map