import * as fs from 'fs';
import * as path from 'path';
export const DAILY_TASK_NAME = 'hippo-daily-runner';
function defaultRegistry() {
    return {
        version: 1,
        workspaces: [],
    };
}
export function workspaceRegistryPath(globalRoot) {
    return path.join(globalRoot, 'workspaces.json');
}
function normalizeWorkspace(projectDir) {
    return path.resolve(projectDir).replace(/\\/g, '/');
}
export function loadWorkspaceRegistry(globalRoot) {
    const registryPath = workspaceRegistryPath(globalRoot);
    if (!fs.existsSync(registryPath))
        return defaultRegistry();
    try {
        const parsed = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
        const workspaces = Array.isArray(parsed.workspaces)
            ? [...new Set(parsed.workspaces.map((entry) => normalizeWorkspace(String(entry))).filter(Boolean))].sort()
            : [];
        return {
            version: 1,
            workspaces,
        };
    }
    catch {
        return defaultRegistry();
    }
}
export function saveWorkspaceRegistry(globalRoot, registry) {
    fs.mkdirSync(globalRoot, { recursive: true });
    fs.writeFileSync(workspaceRegistryPath(globalRoot), JSON.stringify({
        version: 1,
        workspaces: [...new Set(registry.workspaces.map(normalizeWorkspace))].sort(),
    }, null, 2) + '\n', 'utf8');
}
export function registerWorkspace(globalRoot, projectDir) {
    const registry = loadWorkspaceRegistry(globalRoot);
    registry.workspaces = [...new Set([...registry.workspaces, normalizeWorkspace(projectDir)])].sort();
    saveWorkspaceRegistry(globalRoot, registry);
    return registry;
}
export function listRegisteredWorkspaces(globalRoot) {
    return loadWorkspaceRegistry(globalRoot).workspaces;
}
export function buildDailyRunnerCommand(projectDir, platform = process.platform) {
    if (platform === 'win32') {
        const resolved = path.win32.resolve(projectDir).replace(/\\/g, '/');
        return `cd /d "${resolved}" && hippo daily-runner`;
    }
    const resolved = path.posix.resolve(projectDir.replace(/\\/g, '/'));
    return `cd "${resolved}" && hippo daily-runner`;
}
export function runDailyMaintenance(workspaces, runCommand) {
    for (const workspace of workspaces) {
        const resolved = normalizeWorkspace(workspace);
        if (!fs.existsSync(path.join(resolved, '.hippo')))
            continue;
        runCommand(resolved, ['learn', '--git', '--days', '1']);
        runCommand(resolved, ['sleep']);
    }
}
//# sourceMappingURL=scheduler.js.map