import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
function isBlank(value) {
    return typeof value !== "string" || value.trim().length === 0;
}
export function managedDependencyStatePath(managedRoot) {
    return path.join(managedRoot, "state.json");
}
export async function readManagedDependencyState(managedRoot) {
    const statePath = managedDependencyStatePath(managedRoot);
    if (!existsSync(statePath)) {
        return { version: 1, records: {} };
    }
    try {
        const content = await readFile(statePath, "utf8");
        const parsed = JSON.parse(content);
        return {
            version: 1,
            records: typeof parsed.records === "object" && parsed.records !== null ? parsed.records : {},
        };
    }
    catch {
        return { version: 1, records: {} };
    }
}
export async function writeManagedDependencyState(managedRoot, state) {
    await mkdir(managedRoot, { recursive: true });
    await writeFile(managedDependencyStatePath(managedRoot), `${JSON.stringify(state, null, 2)}\n`, "utf8");
}
export async function updateManagedDependencyRecord(managedRoot, record) {
    const nextRecord = {
        ...record,
        managedRoot,
        observedAt: record.observedAt,
        resolvedPath: isBlank(record.resolvedPath) ? undefined : record.resolvedPath?.trim(),
        version: isBlank(record.version) ? undefined : record.version?.trim(),
        lastError: isBlank(record.lastError) ? undefined : record.lastError?.trim(),
    };
    const current = await readManagedDependencyState(managedRoot);
    const next = {
        version: 1,
        records: {
            ...current.records,
            [nextRecord.dependencyId]: nextRecord,
        },
    };
    await writeManagedDependencyState(managedRoot, next);
    return next;
}
export async function readManagedDependencyRecord(managedRoot, dependencyId) {
    const state = await readManagedDependencyState(managedRoot);
    return state.records[dependencyId];
}
