/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, readdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { pullFromGist, pushToGist, STATE_SUBDIR } from '../../services/remote-sync.js';
import { getWorkspaceConfigPath, readWorkspaceConfig, WORKSPACE_CONFIG_DIR } from '../../services/workspace-config.js';
import { ensureDir } from '../../services/file-writer.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.sync');
export default class Sync extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        remote: Flags.string({
            summary: messages.getMessage('flags.remote.summary'),
            required: true,
        }),
        pull: Flags.boolean({
            summary: messages.getMessage('flags.pull.summary'),
            default: false,
        }),
        'dry-run': Flags.boolean({
            summary: messages.getMessage('flags.dry-run.summary'),
            default: false,
        }),
    };
    async run() {
        const { flags } = await this.parse(Sync);
        const cwd = process.cwd();
        const stateDir = join(cwd, STATE_SUBDIR);
        const dryRun = flags['dry-run'];
        const { gistId: parsedGistId } = parseRemote(flags.remote);
        if (flags.pull) {
            if (!parsedGistId) {
                this.error('--remote must include a gist ID when using --pull. Example: --remote gist:abc123');
            }
            const result = await pullFromGist(stateDir, parsedGistId, dryRun);
            this.log(messages.getMessage('info.pulled', [String(result.pulled.length), parsedGistId, String(result.conflicts)]));
            return { pulled: result.pulled, conflicts: result.conflicts, gistId: parsedGistId, dryRun, cwd };
        }
        // Push
        const jsonlFiles = existsSync(stateDir) ? readdirSync(stateDir).filter((f) => f.endsWith('.jsonl')) : [];
        if (jsonlFiles.length === 0) {
            this.warn(messages.getMessage('warn.noState'));
            return { pushed: [], dryRun, cwd };
        }
        if (dryRun) {
            this.log(messages.getMessage('info.dryRun', [jsonlFiles.join(', ')]));
            return { pushed: jsonlFiles, dryRun, cwd };
        }
        const result = await pushToGist(stateDir, parsedGistId, dryRun);
        this.log(messages.getMessage('info.pushed', [String(result.pushed.length), result.url]));
        if (result.gistId && result.gistId !== '(new)') {
            persistGistId(cwd, result.gistId);
        }
        return { pushed: result.pushed, gistId: result.gistId, url: result.url, dryRun, cwd };
    }
}
function parseRemote(remote) {
    if (remote.startsWith('gist:')) {
        const gistId = remote.slice('gist:'.length).trim();
        return { gistId: gistId || undefined };
    }
    return {};
}
function persistGistId(cwd, gistId) {
    const configPath = getWorkspaceConfigPath(cwd);
    if (!existsSync(configPath))
        return;
    const existing = readWorkspaceConfig(cwd);
    if (!existing)
        return;
    const updated = { ...existing, remote: { ...(existing.remote ?? {}), gistId } };
    ensureDir(join(cwd, WORKSPACE_CONFIG_DIR));
    writeFileSync(configPath, `${JSON.stringify(updated, null, 2)}\n`, 'utf8');
}
//# sourceMappingURL=sync.js.map