import { getSession } from "../lib/neo4j.js";
export async function projectGet(projectId, accountId) {
    const session = getSession();
    try {
        // Fetch the project node (must have :Project label)
        const projectResult = await session.run(`MATCH (p:Project {taskId: $projectId, accountId: $accountId}) RETURN p`, { projectId, accountId });
        if (projectResult.records.length === 0) {
            throw new Error(`ProjectNotFound: ${projectId}`);
        }
        const p = projectResult.records[0].get("p").properties;
        // Fetch children with their blockers
        const childrenResult = await session.run(`MATCH (proj:Project {taskId: $projectId, accountId: $accountId})-[:HAS_TASK]->(child:Task)
       OPTIONAL MATCH (blocker:Task)-[:BLOCKS]->(child)
       WHERE blocker.status IN ['pending', 'active']
       RETURN child,
         collect(DISTINCT blocker.taskId) AS blockedByIds
       ORDER BY
         CASE child.priority
           WHEN 'urgent' THEN 0
           WHEN 'high' THEN 1
           WHEN 'normal' THEN 2
           WHEN 'low' THEN 3
           ELSE 4
         END,
         child.createdAt`, { projectId, accountId });
        const children = childrenResult.records.map((rec) => {
            const c = rec.get("child").properties;
            const blockedByIds = rec.get("blockedByIds").filter((id) => id !== null);
            const child = {
                taskId: c.taskId,
                name: c.name,
                status: c.status,
                priority: c.priority,
                blockedBy: blockedByIds,
            };
            if (c.dueDate)
                child.dueDate = c.dueDate;
            return child;
        });
        // Compute health
        const totalTasks = children.length;
        const completedTasks = children.filter((c) => c.status === "completed").length;
        const overdueTasks = children.filter((c) => {
            if (!c.dueDate || c.status === "completed")
                return false;
            return new Date(c.dueDate) < new Date();
        }).length;
        const blockedTasks = children.filter((c) => c.blockedBy.length > 0).length;
        let daysSinceLastProgress = null;
        const completedChildren = children.filter((c) => c.status === "completed");
        if (completedChildren.length > 0) {
            // Approximate: use project's updatedAt as proxy for last progress
            // (full computation would need child updatedAt, not returned in this query)
            daysSinceLastProgress = null;
        }
        let signal = "green";
        if (totalTasks === 0) {
            signal = "grey";
        }
        else if (overdueTasks > 1 || (daysSinceLastProgress !== null && daysSinceLastProgress >= 7)) {
            signal = "red";
        }
        else if (overdueTasks > 0 || blockedTasks > 0) {
            signal = "amber";
        }
        const health = {
            signal,
            totalTasks,
            completedTasks,
            overdueTasks,
            blockedTasks,
            daysSinceLastProgress,
        };
        // Fetch non-HAS_TASK relationships (RAISED_BY, AFFECTS, PART_OF)
        const relResult = await session.run(`MATCH (proj:Project {taskId: $projectId, accountId: $accountId})-[r]->(target)
       WHERE type(r) <> 'HAS_TASK'
       RETURN type(r) AS relType, labels(target) AS targetLabels, elementId(target) AS targetId,
              target.name AS targetName, target.givenName AS targetGivenName`, { projectId, accountId });
        const relationships = relResult.records.map((rec) => {
            const targetLabels = rec.get("targetLabels");
            const targetLabel = targetLabels[0] ?? "Unknown";
            const targetId = rec.get("targetId");
            const targetName = rec.get("targetName") ??
                rec.get("targetGivenName") ??
                targetId;
            return { type: rec.get("relType"), targetLabel, targetId, targetName };
        });
        const detail = {
            projectId: p.taskId,
            name: p.name,
            description: p.description,
            tier: p.tier,
            phase: p.phase,
            status: p.status,
            createdAt: p.createdAt,
            updatedAt: p.updatedAt,
            health,
            children,
            relationships,
        };
        if (p.clientRef)
            detail.clientRef = p.clientRef;
        if (p.targetDate)
            detail.targetDate = p.targetDate;
        if (p.dueDate)
            detail.dueDate = p.dueDate;
        if (p.notes)
            detail.notes = p.notes;
        console.error(`project-get: returned ${projectId} with ${children.length} children`);
        return detail;
    }
    catch (err) {
        if (err instanceof Error && err.message.startsWith("ProjectNotFound:")) {
            console.error(`project-get: failed — ${err.message}`);
        }
        else {
            console.error(`project-get: failed — ${err instanceof Error ? err.message : String(err)}`);
        }
        throw err;
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=project-get.js.map