/**
 * schedules/loader.ts
 *
 * Loads and validates config/schedules.yaml.
 *
 * The schedule config drives both the GitHub Actions cron workflow
 * (which reads enabled schedules to build a matrix) and the digest
 * script (which reads the digest section for lookback and delivery).
 *
 * @see docs/design-docs/report-store/implementation.md — Phase 5
 */
import { existsSync, readFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import { load } from "js-yaml";
import { interpolate } from "../interpolate.js";
import { tryLoadConfigFile } from "../pipeline/compiler/config-loader.js";
import { SchedulesFileSchema, } from "./schema.js";
// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------
const __dirname = dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = resolve(__dirname, "..", "..");
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Find a schedule entry by name.
 */
export function findSchedule(name, configPath) {
    const config = loadSchedules(configPath);
    if (!config)
        return undefined;
    return config.schedules.find((s) => s.name === name);
}
/**
 * Get the digest configuration, if enabled.
 */
export function getDigestConfig(configPath) {
    const config = loadSchedules(configPath);
    if (!config?.digest?.enabled)
        return null;
    return config.digest;
}
/**
 * Get all enabled schedule entries.
 */
export function getEnabledSchedules(configPath) {
    const config = loadSchedules(configPath);
    if (!config)
        return [];
    return config.schedules.filter((s) => s.enabled);
}
/**
 * Load and validate the schedule configuration.
 *
 * @param configPath - Override the default config file location
 * @returns Parsed and validated schedules file, or null if not found/invalid
 */
export function loadSchedules(configPath) {
    try {
        let data;
        if (configPath) {
            // Explicit path override (used by tests) — read directly
            if (!existsSync(configPath))
                return null;
            data = load(readFileSync(configPath, "utf-8"));
        }
        else {
            // Default: use unified config loader
            const loaded = tryLoadConfigFile("schedules", PACKAGE_ROOT);
            if (!loaded)
                return null;
            data = loaded.data;
        }
        const interpolated = interpolate(data);
        return SchedulesFileSchema.parse(interpolated);
    }
    catch (error) {
        console.warn("Failed to load schedules config:", error instanceof Error ? error.message : error);
        return null;
    }
}
