/*
 * 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 { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { PLUGIN_VERSION } from '../version.js';
import { ensureDir } from './file-writer.js';
import { listRecords, recordPath } from './orchestration-records.js';
import { listTasks, taskStatePath } from './task-state.js';
import { readWorkspaceConfig } from './workspace-config.js';
export function exportWorkspace(cwd) {
    return {
        version: PLUGIN_VERSION,
        exportedAt: new Date().toISOString(),
        source: cwd,
        config: readWorkspaceConfig(cwd),
        state: {
            tasks: listTasks(cwd),
            decisions: listRecords(cwd, 'decision'),
            evidence: listRecords(cwd, 'evidence'),
            handoffs: listRecords(cwd, 'handoff'),
            reviews: readReviews(cwd),
        },
    };
}
export function importWorkspace(cwd, bundle, opts) {
    validateBundle(bundle);
    const existing = {
        tasks: new Set(listTasks(cwd).map((r) => r.id)),
        decisions: new Set(listRecords(cwd, 'decision').map((r) => r.id)),
        evidence: new Set(listRecords(cwd, 'evidence').map((r) => r.id)),
        handoffs: new Set(listRecords(cwd, 'handoff').map((r) => r.id)),
        reviews: new Set(readReviews(cwd).map((r) => String(r['id'] ?? ''))),
    };
    const result = {
        imported: { tasks: 0, decisions: 0, evidence: 0, handoffs: 0, reviews: 0 },
        skipped: { tasks: 0, decisions: 0, evidence: 0, handoffs: 0, reviews: 0 },
        dryRun: opts.dryRun,
    };
    if (!opts.dryRun)
        ensureStateDir(cwd);
    const taskCounts = importRecords(bundle.state.tasks, existing.tasks, taskStatePath(cwd), opts);
    const decisionCounts = importRecords(bundle.state.decisions, existing.decisions, recordPath(cwd, 'decision'), opts);
    const evidenceCounts = importRecords(bundle.state.evidence, existing.evidence, recordPath(cwd, 'evidence'), opts);
    const handoffCounts = importRecords(bundle.state.handoffs, existing.handoffs, recordPath(cwd, 'handoff'), opts);
    const reviewCounts = importReviewRecords(bundle.state.reviews, existing.reviews, reviewsFilePath(cwd), opts);
    result.imported = {
        tasks: taskCounts.imported,
        decisions: decisionCounts.imported,
        evidence: evidenceCounts.imported,
        handoffs: handoffCounts.imported,
        reviews: reviewCounts.imported,
    };
    result.skipped = {
        tasks: taskCounts.skipped,
        decisions: decisionCounts.skipped,
        evidence: evidenceCounts.skipped,
        handoffs: handoffCounts.skipped,
        reviews: reviewCounts.skipped,
    };
    return result;
}
function importRecords(records, existingIds, filePath, opts) {
    let imported = 0;
    let skipped = 0;
    for (const record of records) {
        if (existingIds.has(record.id) && opts.onConflict === 'skip') {
            skipped++;
            continue;
        }
        if (!opts.dryRun)
            appendJsonl(filePath, record);
        imported++;
    }
    return { imported, skipped };
}
function importReviewRecords(records, existingIds, filePath, opts) {
    let imported = 0;
    let skipped = 0;
    for (const record of records) {
        const id = String(record['id'] ?? '');
        if (id && existingIds.has(id) && opts.onConflict === 'skip') {
            skipped++;
            continue;
        }
        if (!opts.dryRun)
            appendJsonl(filePath, record);
        imported++;
    }
    return { imported, skipped };
}
function validateBundle(bundle) {
    if (!bundle || typeof bundle !== 'object') {
        throw new Error('Invalid export bundle: must be a JSON object.');
    }
    const b = bundle;
    if (typeof b['version'] !== 'string' || !b['version']) {
        throw new Error('Invalid export bundle: missing or empty "version" field.');
    }
    if (typeof b['exportedAt'] !== 'string' || !b['exportedAt']) {
        throw new Error('Invalid export bundle: missing or empty "exportedAt" field.');
    }
    if (!b['state'] || typeof b['state'] !== 'object') {
        throw new Error('Invalid export bundle: missing "state" object.');
    }
    const state = b['state'];
    for (const key of ['tasks', 'decisions', 'evidence', 'handoffs', 'reviews']) {
        if (!Array.isArray(state[key])) {
            throw new Error(`Invalid export bundle: state.${key} must be an array.`);
        }
    }
}
function readReviews(cwd) {
    const file = reviewsFilePath(cwd);
    if (!existsSync(file))
        return [];
    const content = readFileSync(file, 'utf8').trim();
    if (!content)
        return [];
    return content.split('\n').map((line) => JSON.parse(line));
}
function reviewsFilePath(cwd) {
    return join(cwd, '.setup-agents', 'state', 'reviews.jsonl');
}
function ensureStateDir(cwd) {
    ensureDir(join(cwd, '.setup-agents', 'state'));
}
function appendJsonl(filePath, record) {
    if (!existsSync(filePath))
        writeFileSync(filePath, '');
    appendFileSync(filePath, `${JSON.stringify(record)}\n`);
}
//# sourceMappingURL=export-import.js.map