"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.solveTests = exports.validateTests = exports.generateTests = exports.createTemplate = void 0;
const helpers_1 = require("./helpers");
const logger_1 = require("./logger");
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const createTemplate = (directory) => {
    logger_1.logger.info('Creating problem template...');
    try {
        const problemDir = path_1.default.resolve(process.cwd(), directory);
        const templateDir = path_1.default.resolve(__dirname, '../template');
        fs_1.default.mkdirSync(problemDir, { recursive: true });
        (0, helpers_1.copyTemplate)(templateDir, problemDir);
        logTemplateCreationSuccess(directory);
    }
    catch (error) {
        handleTemplateCreationError(error);
    }
};
exports.createTemplate = createTemplate;
function logTemplateCreationSuccess(directory) {
    logger_1.logger.info('Next steps:');
    logger_1.logger.log(`  1. cd ${directory}`);
    logger_1.logger.log(`  2. Edit config.json to configure your problem`);
    logger_1.logger.log(`  3. Run ${logger_1.logger.highlight('polyman generate-tests')}`);
}
function handleTemplateCreationError(error) {
    const message = error instanceof Error ? error.message : String(error);
    logger_1.logger.error(message);
    process.exit(1);
}
const generateTests = async (generatorName) => {
    logger_1.logger.section('Test Generation');
    try {
        const { generators } = (0, helpers_1.readConfigFile)();
        validateGeneratorsExist(generators);
        logger_1.logger.info(`Found ${generators.length} generator(s)`);
        await runMatchingGenerators(generators, generatorName);
        logger_1.logger.success('All test cases generated successfully!');
    }
    catch (error) {
        handleGenerationError(error);
    }
};
exports.generateTests = generateTests;
function validateGeneratorsExist(generators) {
    if (!generators || generators.length === 0) {
        logger_1.logger.warning('No test generators defined in the configuration file.');
        process.exit(0);
    }
}
async function runMatchingGenerators(generators, generatorName) {
    for (const generator of generators) {
        if (generatorName === 'all' || generator.name === generatorName) {
            await (0, helpers_1.runGenerator)(generator);
        }
    }
}
function handleGenerationError(error) {
    const message = error instanceof Error ? error.message : String(error);
    logger_1.logger.error(`Failed to generate tests: ${message}`);
    process.exit(1);
}
const validateTests = async (arg) => {
    logger_1.logger.section('Test Validation');
    try {
        const config = (0, helpers_1.readConfigFile)();
        ensureValidatorExists(config.validator);
        if (arg === 'all') {
            await validateAllTests(config.validator);
        }
        else if (isNumeric(arg)) {
            await validateSingleTest(config.validator, parseInt(arg, 10));
        }
        else {
            await validateGeneratorTests(config, arg);
        }
    }
    catch (error) {
        handleValidationError(error);
    }
};
exports.validateTests = validateTests;
function ensureValidatorExists(validator) {
    if (!validator) {
        throw new Error('No validator defined in the configuration file.');
    }
}
function isNumeric(value) {
    return !isNaN(parseInt(value, 10));
}
async function validateAllTests(validator) {
    await (0, helpers_1.runValidator)(validator);
    logger_1.logger.success('All tests validated successfully!');
}
async function validateSingleTest(validator, testNumber) {
    await (0, helpers_1.runValidator)(validator, testNumber, testNumber);
    logger_1.logger.success(`Test ${testNumber} validated successfully!`);
}
async function validateGeneratorTests(config, generatorName) {
    const generator = config.generators?.find(g => g.name === generatorName);
    if (!generator) {
        throw new Error(`No generator named "${generatorName}" found in the configuration file.`);
    }
    const [start, end] = generator['tests-range'];
    await (0, helpers_1.runValidator)(config.validator, start, end);
    logger_1.logger.success(`Tests generated by "${generatorName}" validated successfully!`);
}
function handleValidationError(error) {
    const message = error instanceof Error ? error.message : String(error);
    logger_1.logger.error(`Failed to validate tests: ${message}`);
    process.exit(1);
}
const solveTests = async (solutionName, arg) => {
    logger_1.logger.section(`Running Solution: ${solutionName}`);
    try {
        const config = (0, helpers_1.readConfigFile)();
        validateSolutionsExist(config.solutions);
        const matchingSolutions = findMatchingSolutions(config.solutions, solutionName);
        if (arg === 'all') {
            await runSolutionsOnAllTests(matchingSolutions, config);
        }
        else if (isNumeric(arg)) {
            await runSolutionsOnSingleTest(matchingSolutions, config, parseInt(arg, 10));
        }
        else {
            await runSolutionsOnGeneratorTests(matchingSolutions, config, arg);
        }
        logger_1.logger.success('Solutions run completed successfully!');
    }
    catch (error) {
        handleSolutionError(error);
    }
};
exports.solveTests = solveTests;
function validateSolutionsExist(solutions) {
    if (!solutions || solutions.length === 0) {
        throw new Error('No solutions defined in the configuration file.');
    }
}
function findMatchingSolutions(solutions, solutionName) {
    const matching = solutions.filter(s => solutionName === 'all' || s.name === solutionName);
    if (matching.length === 0) {
        throw new Error(`Solution named "${solutionName}" not found or no solutions defined.`);
    }
    return matching;
}
async function runSolutionsOnAllTests(solutions, config) {
    for (const solution of solutions) {
        await (0, helpers_1.runSolution)(solution, config['time-limit'], config['memory-limit']);
    }
}
async function runSolutionsOnSingleTest(solutions, config, testNumber) {
    for (const solution of solutions) {
        await (0, helpers_1.runSolution)(solution, config['time-limit'], config['memory-limit'], testNumber, testNumber);
    }
}
async function runSolutionsOnGeneratorTests(solutions, config, generatorName) {
    const generator = config.generators?.find(g => g.name === generatorName);
    if (!generator) {
        throw new Error(`No generator named "${generatorName}" found in the configuration file.`);
    }
    const [start, end] = generator['tests-range'];
    for (const solution of solutions) {
        await (0, helpers_1.runSolution)(solution, config['time-limit'], config['memory-limit'], start, end);
    }
}
function handleSolutionError(error) {
    const message = error instanceof Error ? error.message : String(error);
    logger_1.logger.error(`Failed to run solution: ${message}`);
    process.exit(1);
}
//# sourceMappingURL=actions-refactored.js.map