/**
 * Sync measured baselines into .samplebeacon/baseline.json
 */

const fs = require('fs');
const path = require('path');
const { loadSamplebeaconConfig } = require('./config');
const { checkJestBaseline, parseJestSummary, runCommand } = require('./rules/jest-baseline');

async function syncJestBaseline(baseDir, options = {}) {
    const config = loadSamplebeaconConfig(baseDir, options.config);
    const ruleOptions = config.rules?.['jest-baseline'] || {};
    const testCommand = options.testCommand
        || ruleOptions.testCommand
        || 'npm test -- --no-coverage --passWithNoTests';

    const result = await runCommand(baseDir, testCommand, options.timeoutMs || 120000);
    const summary = parseJestSummary(result.output);

    if (!summary) {
        throw new Error('Could not parse Jest summary — run npm test locally and check output format');
    }

    if (summary.testsFailed > 0 || result.code !== 0) {
        throw new Error(
            `Jest reported failures (${summary.testsPassed}/${summary.testsTotal} passed) — fix tests before syncing baseline`
        );
    }

    const baseline = {
        ...config.baseline,
        jestTestsPassing: summary.testsPassed,
        jestTestsLabel: `${summary.testsPassed}/${summary.testsTotal}`,
        jestSuites: summary.suitesPassed ?? config.baseline.jestSuites ?? null,
        syncedAt: new Date().toISOString()
    };

    fs.mkdirSync(path.dirname(config.baselinePath), { recursive: true });
    fs.writeFileSync(config.baselinePath, `${JSON.stringify(baseline, null, 2)}\n`, 'utf8');

    return {
        baselinePath: config.baselinePath,
        summary,
        baseline
    };
}

async function verifyJestBaseline(baseDir, options = {}) {
    const config = loadSamplebeaconConfig(baseDir, options.config);
    return checkJestBaseline(baseDir, {
        baseline: config.baseline,
        runTests: true,
        testCommand: options.testCommand || config.rules?.['jest-baseline']?.testCommand,
        timeoutMs: options.timeoutMs
    });
}

module.exports = {
    syncJestBaseline,
    verifyJestBaseline
};
