import { knowledgeStore, readJson, writeJson, projectDataDir } from '../storage/index.js';
import { compactResult, formatKeyValue } from './output-formatter.js';
// ---------------------------------------------------------------------------
// Storage helpers
// ---------------------------------------------------------------------------
function scopeFile(projectId) {
    return `${projectDataDir(projectId)}/scope.json`;
}
function backlogFile(projectId) {
    return `${projectDataDir(projectId)}/backlog.json`;
}
async function readScope(projectId) {
    return readJson(scopeFile(projectId), null);
}
async function writeScope(projectId, scope) {
    await writeJson(scopeFile(projectId), scope);
}
async function readBacklog(projectId) {
    return readJson(backlogFile(projectId), []);
}
async function writeBacklog(projectId, backlog) {
    await writeJson(backlogFile(projectId), backlog);
}
// ---------------------------------------------------------------------------
// Operation handlers
// ---------------------------------------------------------------------------
async function handleView(projectId) {
    const [scope, backlog] = await Promise.all([readScope(projectId), readBacklog(projectId)]);
    const message = scope
        ? 'Scope loaded successfully. Use operation "list_backlog" to see deferred items.'
        : 'No scope defined yet. Use init_constitution to define the project scope.';
    return compactResult(formatKeyValue({ projectId, backlogCount: backlog.length, message }, 'Scope') +
        (scope
            ? `\n\n**Scope**: platforms=[${scope.platforms.join(', ')}] users=[${scope.targetUsers.join(', ')}]`
            : ''));
}
async function handleListBacklog(projectId) {
    const backlog = await readBacklog(projectId);
    const message = backlog.length === 0 ? 'Backlog is empty.' : `${backlog.length} item(s) in backlog.`;
    return compactResult(formatKeyValue({ projectId, backlogCount: backlog.length, message }, 'Backlog') +
        (backlog.length > 0
            ? '\n\n' + backlog.map((item) => `- [${item.id}] ${item.description}`).join('\n')
            : ''));
}
async function handleAddToBacklog(projectId, params) {
    const { itemDescription, exclusionReason, specId } = params;
    if (!itemDescription) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'itemDescription is required for add_to_backlog operation.',
                },
            ],
            isError: true,
        };
    }
    if (!exclusionReason) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'exclusionReason is required for add_to_backlog operation.',
                },
            ],
            isError: true,
        };
    }
    const backlog = await readBacklog(projectId);
    const id = `backlog-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
    const item = {
        id,
        description: itemDescription,
        exclusionReason,
        dateAdded: new Date().toISOString(),
        ...(specId ? { specId } : {}),
    };
    backlog.push(item);
    await writeBacklog(projectId, backlog);
    return compactResult(formatKeyValue({
        projectId,
        backlogCount: backlog.length,
        addedId: item.id,
        message: `Item added to backlog. Backlog now has ${backlog.length} item(s).`,
    }, 'Backlog') + `\n\n**Added**: ${item.description} (reason: ${item.exclusionReason})`);
}
async function handleProposeChange(projectId, params) {
    const { newScope, changeReason, approvedBy } = params;
    if (!newScope) {
        return {
            content: [{ type: 'text', text: 'newScope is required for propose_change operation.' }],
            isError: true,
        };
    }
    if (!changeReason) {
        return {
            content: [{ type: 'text', text: 'changeReason is required for propose_change operation.' }],
            isError: true,
        };
    }
    if (!approvedBy) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'approvedBy is required for propose_change operation — scope changes must be explicitly approved.',
                },
            ],
            isError: true,
        };
    }
    const existing = await readScope(projectId);
    const decision = {
        type: 'change',
        reason: changeReason,
        date: new Date().toISOString(),
        approvedBy,
    };
    const now = new Date().toISOString();
    const updated = {
        platforms: newScope.platforms ?? existing?.platforms ?? [],
        targetUsers: newScope.targetUsers ?? existing?.targetUsers ?? [],
        primaryProblem: newScope.primaryProblem ?? existing?.primaryProblem ?? '',
        definedAt: existing?.definedAt ?? now,
        changeHistory: [...(existing?.changeHistory ?? []), decision],
    };
    await writeScope(projectId, updated);
    return compactResult(formatKeyValue({
        projectId,
        message: 'Scope change approved and recorded.',
        decisionType: decision.type,
        approvedBy: decision.approvedBy,
        changeHistoryCount: updated.changeHistory?.length ?? 0,
    }, 'Scope Change') +
        `\n\n**New Scope**: platforms=[${updated.platforms.join(', ')}] users=[${updated.targetUsers.join(', ')}]`);
}
// ---------------------------------------------------------------------------
// Main handler
// ---------------------------------------------------------------------------
export async function handleManageScope(params) {
    const { projectId, operation } = params;
    try {
        const knowledge = await knowledgeStore.getKnowledge(projectId);
        if (!knowledge) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `Project "${projectId}" not found. Run init_project first.`,
                    },
                ],
                isError: true,
            };
        }
        switch (operation) {
            case 'view':
                return await handleView(projectId);
            case 'list_backlog':
                return await handleListBacklog(projectId);
            case 'add_to_backlog':
                return await handleAddToBacklog(projectId, params);
            case 'propose_change':
                return await handleProposeChange(projectId, params);
            /* v8 ignore start */
            default: {
                const _exhaustive = operation;
                return {
                    content: [{ type: 'text', text: `Unknown operation: ${String(_exhaustive)}` }],
                    isError: true,
                };
            }
            /* v8 ignore stop */
        }
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Internal error: ${message}` }],
            isError: true,
        };
    }
}
//# sourceMappingURL=manage-scope.js.map