import path from "node:path";
import { createPersistedProjectRecord, createPersistedWorkspaceRecord, } from "./workspace-registry.js";
import { buildProjectPlacementForCwd, deriveProjectKind, deriveProjectRootPath, deriveWorkspaceDisplayName, deriveWorkspaceId, deriveWorkspaceKind, normalizeWorkspaceId, } from "./workspace-registry-model.js";
function minIsoDate(left, right) {
    if (!left) {
        return right;
    }
    if (!right) {
        return left;
    }
    return Date.parse(left) <= Date.parse(right) ? left : right;
}
function maxIsoDate(left, right) {
    if (!left) {
        return right;
    }
    if (!right) {
        return left;
    }
    return Date.parse(left) >= Date.parse(right) ? left : right;
}
function resolveAgentCreatedAt(record) {
    return record.createdAt || record.updatedAt || new Date(0).toISOString();
}
function resolveAgentUpdatedAt(record) {
    return record.lastActivityAt || record.updatedAt || record.createdAt || new Date(0).toISOString();
}
export async function bootstrapWorkspaceRegistries(options) {
    const [projectsExists, workspacesExists] = await Promise.all([
        options.projectRegistry.existsOnDisk(),
        options.workspaceRegistry.existsOnDisk(),
    ]);
    await Promise.all([options.projectRegistry.initialize(), options.workspaceRegistry.initialize()]);
    if (projectsExists && workspacesExists) {
        return;
    }
    const records = await options.agentStorage.list();
    const activeRecords = records.filter((record) => !record.archivedAt);
    const recordsByWorkspaceId = new Map();
    for (const record of activeRecords) {
        const normalizedCwd = normalizeWorkspaceId(record.cwd);
        const placement = await buildProjectPlacementForCwd({
            cwd: normalizedCwd,
            seaworkHome: options.seaworkHome,
        });
        const workspaceId = deriveWorkspaceId(normalizedCwd, placement.checkout);
        const existing = recordsByWorkspaceId.get(workspaceId) ?? { placement, records: [] };
        existing.records.push(record);
        recordsByWorkspaceId.set(workspaceId, existing);
    }
    const projectRanges = new Map();
    for (const [workspaceId, entry] of recordsByWorkspaceId.entries()) {
        const { placement, records: workspaceRecords } = entry;
        let workspaceCreatedAt = null;
        let workspaceUpdatedAt = null;
        for (const record of workspaceRecords) {
            workspaceCreatedAt = minIsoDate(workspaceCreatedAt, resolveAgentCreatedAt(record));
            workspaceUpdatedAt = maxIsoDate(workspaceUpdatedAt, resolveAgentUpdatedAt(record));
        }
        const createdAt = workspaceCreatedAt ?? new Date().toISOString();
        const updatedAt = workspaceUpdatedAt ?? createdAt;
        await options.workspaceRegistry.upsert(createPersistedWorkspaceRecord({
            workspaceId,
            projectId: placement.projectKey,
            cwd: workspaceId,
            kind: deriveWorkspaceKind(placement.checkout),
            displayName: deriveWorkspaceDisplayName({
                cwd: workspaceId,
                checkout: placement.checkout,
            }),
            createdAt,
            updatedAt,
        }));
        const existingProjectRange = projectRanges.get(placement.projectKey) ?? {
            createdAt: null,
            updatedAt: null,
        };
        existingProjectRange.createdAt = minIsoDate(existingProjectRange.createdAt, createdAt);
        existingProjectRange.updatedAt = maxIsoDate(existingProjectRange.updatedAt, updatedAt);
        projectRanges.set(placement.projectKey, existingProjectRange);
        // Preserve user-set fields from any existing project record so a
        // partial-registry recovery (e.g. workspaces.json missing but
        // projects.json present) doesn't silently wipe out worktreeParentDir.
        const existingProjectRecord = await options.projectRegistry.get(placement.projectKey);
        await options.projectRegistry.upsert(createPersistedProjectRecord({
            projectId: placement.projectKey,
            rootPath: deriveProjectRootPath({
                cwd: workspaceId,
                checkout: placement.checkout,
            }),
            kind: deriveProjectKind(placement.checkout),
            displayName: placement.projectName,
            createdAt: existingProjectRange.createdAt ?? createdAt,
            updatedAt: existingProjectRange.updatedAt ?? updatedAt,
            worktreeParentDir: existingProjectRecord?.worktreeParentDir ?? null,
        }));
    }
    options.logger.info({
        projectsFile: path.join(options.seaworkHome, "projects", "projects.json"),
        workspacesFile: path.join(options.seaworkHome, "projects", "workspaces.json"),
        materializedProjects: projectRanges.size,
        materializedWorkspaces: recordsByWorkspaceId.size,
    }, "Workspace registries bootstrapped from existing agent storage");
}
//# sourceMappingURL=workspace-registry-bootstrap.js.map