import { getSession } from "../lib/neo4j.js";
import { computeEmbedding } from "../lib/embeddings.js";
export async function projectComplete(params) {
    const { projectId, accountId, note } = params;
    const session = getSession();
    try {
        // Fetch the project and its children
        const projectResult = await session.run(`MATCH (p:Project {taskId: $projectId, accountId: $accountId})
       OPTIONAL MATCH (p)-[:HAS_TASK]->(child:Task)
       RETURN p,
         collect({taskId: child.taskId, name: child.name, status: child.status}) AS children`, { projectId, accountId });
        if (projectResult.records.length === 0) {
            throw new Error(`ProjectNotFound: ${projectId}`);
        }
        const rec = projectResult.records[0];
        const p = rec.get("p").properties;
        const children = rec.get("children")
            .filter((c) => c.taskId !== null);
        const totalTasks = children.length;
        const completedTasks = children.filter((c) => c.status === "completed" || c.status === "cancelled").length;
        const incompleteChildren = children
            .filter((c) => c.status !== "completed" && c.status !== "cancelled")
            .map((c) => ({ taskId: c.taskId, name: c.name, status: c.status }));
        // Build completion note
        const now = new Date().toISOString();
        const timestamp = now.slice(0, 16).replace("T", " ");
        const deferred = incompleteChildren.length;
        const completionNote = `[${timestamp}] [PROJECT:COMPLETE] ${p.name} — ${completedTasks}/${totalTasks} tasks, ${deferred} deferred`;
        const userNote = note ? `\n[${timestamp}] ${note}` : "";
        const currentNotes = p.notes ?? "";
        const newNotes = currentNotes
            ? `${currentNotes}\n${completionNote}${userNote}`
            : `${completionNote}${userNote}`;
        // Re-embed
        const embeddingText = `Project: ${p.name} — ${p.description} tier: ${p.tier} status: completed ${newNotes}`;
        const embedding = await computeEmbedding(embeddingText);
        const setClauses = [
            "p.status = 'completed'",
            "p.phase = 'complete'",
            "p.notes = $notes",
            "p.updatedAt = $updatedAt",
        ];
        const queryParams = {
            projectId,
            accountId,
            notes: newNotes,
            updatedAt: now,
        };
        if (embedding.length > 0) {
            setClauses.push("p.embedding = $embedding");
            queryParams.embedding = embedding;
        }
        await session.run(`MATCH (p:Project {taskId: $projectId, accountId: $accountId})
       SET ${setClauses.join(", ")}`, queryParams);
        console.error(`project-complete: ${projectId} completed, ${completedTasks}/${totalTasks} done, ${deferred} incomplete`);
        return {
            projectId,
            completedTasks,
            totalTasks,
            incompleteChildren,
        };
    }
    catch (err) {
        if (err instanceof Error && err.message.startsWith("ProjectNotFound:")) {
            console.error(`project-complete: failed — ${err.message}`);
        }
        else {
            console.error(`project-complete: failed — ${err instanceof Error ? err.message : String(err)}`);
        }
        throw err;
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=project-complete.js.map