/**
 * Core import logic — import tasks from export files.
 *
 * Extracted from CLI import command for dispatch layer access.
 *
 * @task T5323, T5328
 */
import { constants as fsConstants } from 'node:fs';
import { access, readFile } from 'node:fs/promises';
import { getAccessor } from '../store/data-accessor.js';
function generateTaskId(existingIds) {
    let maxNum = 0;
    for (const id of existingIds) {
        const num = parseInt(id.replace('T', ''), 10);
        if (!Number.isNaN(num) && num > maxNum)
            maxNum = num;
    }
    const newId = `T${String(maxNum + 1).padStart(4, '0')}`;
    existingIds.add(newId);
    return newId;
}
/**
 * Import tasks from an export file.
 */
export async function importTasks(params) {
    const { file } = params;
    try {
        await access(file, fsConstants.R_OK);
    }
    catch {
        throw new Error(`Import file not found: ${file}`);
    }
    const content = await readFile(file, 'utf-8');
    let importData;
    try {
        importData = JSON.parse(content);
    }
    catch {
        throw new Error(`Invalid JSON in import file: ${file}`);
    }
    let importTasks;
    if (Array.isArray(importData)) {
        importTasks = importData;
    }
    else if (Array.isArray(importData['tasks'])) {
        importTasks = importData['tasks'];
    }
    else {
        throw new Error('Import file must contain a tasks array');
    }
    if (importTasks.length === 0) {
        return { imported: 0, skipped: 0, renamed: [], totalTasks: 0, dryRun: params.dryRun };
    }
    const accessor = await getAccessor(params.cwd);
    const { tasks: existingTasks } = await accessor.queryTasks({});
    const existingIds = new Set(existingTasks.map((t) => t.id));
    const duplicateStrategy = params.onDuplicate ?? 'skip';
    const parentId = params.parent;
    const phase = params.phase;
    const addLabel = params.addLabel;
    const idMapping = new Map();
    const imported = [];
    const skipped = [];
    const renamed = [];
    for (const importTask of importTasks) {
        const isDuplicate = existingIds.has(importTask.id);
        if (isDuplicate) {
            switch (duplicateStrategy) {
                case 'skip': {
                    skipped.push(importTask.id);
                    continue;
                }
                case 'overwrite': {
                    // Will be upserted below
                    break;
                }
                case 'rename': {
                    const newId = generateTaskId(existingIds);
                    idMapping.set(importTask.id, newId);
                    renamed.push({ oldId: importTask.id, newId });
                    importTask.id = newId;
                    break;
                }
            }
        }
        if (parentId)
            importTask.parentId = parentId;
        if (phase)
            importTask.phase = phase;
        if (addLabel) {
            importTask.labels = importTask.labels ?? [];
            if (!importTask.labels.includes(addLabel)) {
                importTask.labels.push(addLabel);
            }
        }
        importTask.status = importTask.status ?? 'pending';
        importTask.priority = importTask.priority ?? 'medium';
        importTask.createdAt = importTask.createdAt ?? new Date().toISOString();
        importTask.updatedAt = new Date().toISOString();
        if (importTask.depends) {
            importTask.depends = importTask.depends.map((depId) => idMapping.get(depId) ?? depId);
        }
        if (importTask.parentId && idMapping.has(importTask.parentId)) {
            importTask.parentId = idMapping.get(importTask.parentId);
        }
        existingIds.add(importTask.id);
        imported.push(importTask);
    }
    const totalTasks = existingTasks.length + imported.filter((t) => !existingTasks.some((e) => e.id === t.id)).length;
    if (params.dryRun) {
        return {
            imported: imported.length,
            skipped: skipped.length,
            renamed,
            totalTasks,
            dryRun: true,
        };
    }
    for (const task of imported) {
        await accessor.upsertSingleTask(task);
    }
    return {
        imported: imported.length,
        skipped: skipped.length,
        renamed,
        totalTasks,
    };
}
//# sourceMappingURL=import.js.map