// Onboarding state management — graph-persisted workflow state.
// Purpose-built for Phase 0; migrates to a Workflow node with Task 13.
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const STEP_FIELDS = [
    "step1CompletedAt",
    "step2CompletedAt",
    "step3CompletedAt",
    "step4CompletedAt",
    "step5CompletedAt",
    "step6CompletedAt",
    "step7CompletedAt",
    "step8CompletedAt",
    "step9CompletedAt",
];
// neo4j-driver v5 returns Integer objects for integer properties, not native
// JS numbers. This converts them safely (values 0–9 are well within range).
function toJsNumber(val) {
    if (typeof val === "number")
        return val;
    if (val && typeof val === "object" && "toNumber" in val) {
        return val.toNumber();
    }
    return 0;
}
function recordToState(record) {
    return {
        currentStep: toJsNumber(record.get("currentStep")),
        step1CompletedAt: record.get("step1CompletedAt") ?? null,
        step2CompletedAt: record.get("step2CompletedAt") ?? null,
        step3CompletedAt: record.get("step3CompletedAt") ?? null,
        step4CompletedAt: record.get("step4CompletedAt") ?? null,
        step5CompletedAt: record.get("step5CompletedAt") ?? null,
        step6CompletedAt: record.get("step6CompletedAt") ?? null,
        step7CompletedAt: record.get("step7CompletedAt") ?? null,
        step8CompletedAt: record.get("step8CompletedAt") ?? null,
        step9CompletedAt: record.get("step9CompletedAt") ?? null,
        createdAt: record.get("createdAt") ?? new Date().toISOString(),
        updatedAt: record.get("updatedAt") ?? new Date().toISOString(),
    };
}
function readMigrationStep(accountDir) {
    try {
        const raw = readFileSync(join(accountDir, "account.json"), "utf-8");
        const config = JSON.parse(raw);
        if (typeof config.onboardingStep === "number" && config.onboardingStep > 0) {
            return config.onboardingStep;
        }
    }
    catch {
        // File missing, unreadable, or malformed — no migration data
    }
    return 0;
}
function removeOnboardingStepFromFile(accountDir) {
    try {
        const configPath = join(accountDir, "account.json");
        const raw = readFileSync(configPath, "utf-8");
        const config = JSON.parse(raw);
        if ("onboardingStep" in config) {
            delete config.onboardingStep;
            writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
        }
    }
    catch {
        // Tolerate cleanup failure — graph is the authority now
    }
}
/**
 * Task 562: consume the step-7 completion flag written by setup-tunnel.sh
 * before the service restart. The script runs inside ${BRAND}.service's
 * cgroup and cannot complete the MCP call after dispatching the restart —
 * so it drops a filesystem marker instead. The first read of onboarding
 * state after the restart picks it up, advances the graph via the same
 * CASE-WHEN-NULL cypher as completeOnboardingStep, and deletes the marker.
 *
 * Idempotent at every layer: a missing flag is a no-op; a flag present
 * against an already-completed step is a no-op on the graph (CASE-WHEN-NULL
 * preserves the existing timestamp); a crash between graph write and flag
 * delete re-consumes on the next call with the same no-op outcome.
 */
export async function consumeStep7Flag(session, accountId, accountDir) {
    const flagPath = join(accountDir, "onboarding", "step7-complete");
    if (!existsSync(flagPath))
        return false;
    let completedAt = new Date().toISOString();
    try {
        const raw = readFileSync(flagPath, "utf-8").trim();
        if (raw) {
            const parsed = JSON.parse(raw);
            if (typeof parsed.completedAt === "string") {
                completedAt = parsed.completedAt;
            }
        }
    }
    catch {
        // Malformed flag content still advances state — the flag's presence
        // alone is the authoritative signal; the embedded timestamp is forensic.
    }
    // RETURN count(o) so we can detect the "no OnboardingState node" case
    // where SET is a silent no-op. Without this check, rmSync below would
    // delete the flag against a graph that never applied the write, silently
    // losing the step-7 completion signal forever.
    const result = await session.run(`MATCH (o:OnboardingState {accountId: $accountId})
     SET o.step7CompletedAt = CASE WHEN o.step7CompletedAt IS NULL THEN $completedAt ELSE o.step7CompletedAt END,
         o.currentStep = CASE WHEN 7 > o.currentStep THEN 7 ELSE o.currentStep END,
         o.updatedAt = $completedAt
     RETURN count(o) AS updated`, { accountId, completedAt });
    const updatedRaw = result.records[0]?.get("updated");
    const updated = toJsNumber(updatedRaw);
    if (updated === 0) {
        // No OnboardingState node yet — leave the flag in place so the next
        // reader (after node creation via MERGE in this function's migration
        // branch below) can still consume it.
        console.log(`[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}… step=7 ` +
            `source=filesystem flagPath=${flagPath} skipped=no-node`);
        return false;
    }
    console.log(`[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}… step=7 ` +
        `source=filesystem flagPath=${flagPath} completedAt=${completedAt}`);
    try {
        rmSync(flagPath);
    }
    catch (err) {
        console.error(`[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ` +
            `${err instanceof Error ? err.message : String(err)}`);
    }
    return true;
}
const READ_STATE_QUERY = `MATCH (o:OnboardingState {accountId: $accountId})
       RETURN o.currentStep AS currentStep,
              o.step1CompletedAt AS step1CompletedAt,
              o.step2CompletedAt AS step2CompletedAt,
              o.step3CompletedAt AS step3CompletedAt,
              o.step4CompletedAt AS step4CompletedAt,
              o.step5CompletedAt AS step5CompletedAt,
              o.step6CompletedAt AS step6CompletedAt,
              o.step7CompletedAt AS step7CompletedAt,
              o.step8CompletedAt AS step8CompletedAt,
              o.step9CompletedAt AS step9CompletedAt,
              o.createdAt AS createdAt,
              o.updatedAt AS updatedAt`;
export async function getOnboardingState(sessionFactory, accountId, accountDir) {
    const session = sessionFactory();
    try {
        // Check for existing graph node
        const existing = await session.run(READ_STATE_QUERY, { accountId });
        const nodeExisted = existing.records.length > 0;
        if (nodeExisted) {
            // Task 562: consume setup-tunnel.sh step-7 flag against the existing
            // node. loadOnboardingStep (UI side) usually does this first at session
            // start; this call is defensive in case this read precedes it.
            //
            // Always re-read after the consume attempt. If a concurrent caller
            // consumed the flag between our initial read and our consumeStep7Flag
            // call, consumeStep7Flag returns false (flag gone) but the graph still
            // advanced — returning `existing.records[0]` would hand back the stale
            // pre-consumption record. One extra indexed MATCH is negligible and
            // guarantees the caller sees the authoritative state.
            await consumeStep7Flag(session, accountId, accountDir);
            const refreshed = await session.run(READ_STATE_QUERY, { accountId });
            return recordToState(refreshed.records[0]);
        }
        // No graph node — check for migration from account.json
        const migratedStep = readMigrationStep(accountDir);
        const now = new Date().toISOString();
        // Build step completion timestamps for migrated steps.
        // account.json only stored a step counter, not per-step timestamps,
        // so migrated steps all get the current time — the original times
        // were never recorded.
        const stepProps = {};
        for (let i = 0; i < STEP_FIELDS.length; i++) {
            stepProps[STEP_FIELDS[i]] = i < migratedStep ? now : null;
        }
        // Create the node via MERGE (idempotent under concurrent access)
        const result = await session.run(`MERGE (o:OnboardingState {accountId: $accountId})
       ON CREATE SET
         o.currentStep = $currentStep,
         o.step1CompletedAt = $step1CompletedAt,
         o.step2CompletedAt = $step2CompletedAt,
         o.step3CompletedAt = $step3CompletedAt,
         o.step4CompletedAt = $step4CompletedAt,
         o.step5CompletedAt = $step5CompletedAt,
         o.step6CompletedAt = $step6CompletedAt,
         o.step7CompletedAt = $step7CompletedAt,
         o.step8CompletedAt = $step8CompletedAt,
         o.step9CompletedAt = $step9CompletedAt,
         o.createdAt = $now,
         o.updatedAt = $now
       RETURN o.currentStep AS currentStep,
              o.step1CompletedAt AS step1CompletedAt,
              o.step2CompletedAt AS step2CompletedAt,
              o.step3CompletedAt AS step3CompletedAt,
              o.step4CompletedAt AS step4CompletedAt,
              o.step5CompletedAt AS step5CompletedAt,
              o.step6CompletedAt AS step6CompletedAt,
              o.step7CompletedAt AS step7CompletedAt,
              o.step8CompletedAt AS step8CompletedAt,
              o.step9CompletedAt AS step9CompletedAt,
              o.createdAt AS createdAt,
              o.updatedAt AS updatedAt`, { accountId, currentStep: migratedStep, now, ...stepProps });
        // Clean up account.json if migration happened
        if (migratedStep > 0) {
            removeOnboardingStepFromFile(accountDir);
        }
        return recordToState(result.records[0]);
    }
    finally {
        await session.close();
    }
}
export async function completeOnboardingStep(sessionFactory, accountId, step) {
    if (!Number.isInteger(step) || step < 1 || step > 9) {
        throw new Error("Step must be between 1 and 9");
    }
    const session = sessionFactory();
    try {
        const stepField = STEP_FIELDS[step - 1];
        const now = new Date().toISOString();
        // Single query: MATCH + SET. If no node exists, MATCH returns zero
        // records and we detect that from the result — no separate check needed.
        const result = await session.run(`MATCH (o:OnboardingState {accountId: $accountId})
       SET o.${stepField} = CASE WHEN o.${stepField} IS NULL THEN $now ELSE o.${stepField} END,
           o.currentStep = CASE WHEN $step > o.currentStep THEN $step ELSE o.currentStep END,
           o.updatedAt = $now
       RETURN o.currentStep AS currentStep,
              o.step1CompletedAt AS step1CompletedAt,
              o.step2CompletedAt AS step2CompletedAt,
              o.step3CompletedAt AS step3CompletedAt,
              o.step4CompletedAt AS step4CompletedAt,
              o.step5CompletedAt AS step5CompletedAt,
              o.step6CompletedAt AS step6CompletedAt,
              o.step7CompletedAt AS step7CompletedAt,
              o.step8CompletedAt AS step8CompletedAt,
              o.step9CompletedAt AS step9CompletedAt,
              o.createdAt AS createdAt,
              o.updatedAt AS updatedAt`, { accountId, step, now });
        if (result.records.length === 0) {
            throw new Error("No onboarding state found for this account. Call onboarding-get first.");
        }
        console.log(`[onboarding-step-complete] accountId=${accountId.slice(0, 8)}… ` +
            `step=${step} completedAt=${now}`);
        return recordToState(result.records[0]);
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=onboarding.js.map