import fs from 'node:fs/promises';
import path from 'node:path';
import { ensureDir, readSessionDirEnv, resolveClockStateFile } from './paths.js';
import { buildEmptyState, cleanExpiredTasks, coerceState, nowMs } from './state.js';
import { readJsonFile, writeJsonFileAtomic } from './io.js';
export async function loadClockSessionState(sessionId, config) {
    const sessionDir = readSessionDirEnv();
    if (!sessionDir) {
        return buildEmptyState(sessionId);
    }
    const filePath = resolveClockStateFile(sessionDir, sessionId);
    if (!filePath) {
        return buildEmptyState(sessionId);
    }
    try {
        const raw = await readJsonFile(filePath);
        const state = coerceState(raw, sessionId);
        const at = nowMs();
        const cleaned = cleanExpiredTasks(state.tasks, config, at);
        if (cleaned.length !== state.tasks.length) {
            const next = { ...state, tasks: cleaned, updatedAtMs: at };
            if (!next.tasks.length) {
                await fs.rm(filePath, { force: true });
            }
            else {
                await ensureDir(path.dirname(filePath));
                await writeJsonFileAtomic(filePath, next);
            }
            return next;
        }
        return state;
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error ?? 'unknown');
        if (message.includes('ENOENT')) {
            return buildEmptyState(sessionId);
        }
        return buildEmptyState(sessionId);
    }
}
export async function clearClockSession(sessionId) {
    const sessionDir = readSessionDirEnv();
    if (!sessionDir) {
        return;
    }
    const filePath = resolveClockStateFile(sessionDir, sessionId);
    if (!filePath) {
        return;
    }
    try {
        await fs.rm(filePath, { force: true });
    }
    catch {
        // ignore
    }
}
