"use strict";
/**
 * @file Main entry point for the APIDoc library
 *
 * APIDoc creates documentation from API descriptions in your source code.
 * This is a RESTful web API Documentation Generator with TypeScript support.
 *
 * @package
 * @version 4.0.0
 * @author Href Spa <hola@apidoc.app>
 * @copyright 2025 Href SpA
 * @license MIT
 * @see {@link https://apidocjs.com} Official documentation
 * @see {@link https://github.com/hrefcl/apidoc} GitHub repository
 *
 * This project is a TypeScript refactor inspired by the original apidoc project.
 *
 * @example
 * ```typescript
 * import { createDoc } from '@hrefcl/apidoc';
 *
 * const result = createDoc({
 *   src: ['./src'],
 *   dest: './doc',
 *   name: 'My API'
 * });
 *
 * if (typeof result !== 'boolean') {
 *   console.log('API Documentation generated successfully');
 *   console.log('Data:', result.data);
 *   console.log('Project info:', result.project);
 * }
 * ```
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDoc = createDoc;
const pkgJson = __importStar(require("../package.json"));
const core = __importStar(require("./core/index"));
const defaults = __importStar(require("./defaults"));
const optionsProcessor = __importStar(require("./options"));
const reader_1 = require("./reader");
const writer_1 = __importDefault(require("./writer"));
/**
 * Global application context containing shared instances and configuration
 *
 * @internal
 */
const app = {
    log: {},
    markdownParser: {},
    options: {},
};
/**
 * Global error handler for uncaught exceptions
 * Ensures graceful shutdown and proper error reporting
 *
 * @internal
 */
process.on('uncaughtException', (err) => {
    console.error(new Date().toUTCString() + ' uncaughtException:', err.message);
    console.error(err.stack);
    process.exit(1);
});
/**
 * Creates API documentation from source code comments
 *
 * This is the main entry point for generating API documentation. It processes
 * source files containing API documentation comments and generates HTML output.
 *
 * @param options - Configuration options for documentation generation
 * @param options.src - Source files or directories to process (array or string)
 * @param options.dest - Output directory for generated documentation
 * @param options.name - Name of the API project
 * @param options.version - Version of the API
 * @param options.description - Description of the API project
 * @param options.title - Title for the generated documentation
 * @param options.url - Base URL of the API
 * @param options.sampleUrl - Sample URL for API requests
 * @param options.header - Header configuration object
 * @param options.footer - Footer configuration object
 * @param options.template - Custom template directory
 * @param options.config - Configuration file path
 * @param options.apiprivate - Include private API endpoints
 * @param options.verbose - Enable verbose logging
 * @param options.debug - Enable debug mode
 * @param options.silent - Suppress all output
 * @param options.simulate - Dry run mode (don't write files)
 * @param options.warnError - Treat warnings as errors and exit with error code
 * @param options.markdown - Enable markdown parsing in descriptions
 * @param options.lineEnding - Line ending style (CRLF or LF)
 * @param options.encoding - File encoding (default: utf8)
 *
 * @returns Processing result:
 *   - `ApiDocParseResult` object with `data` and `project` properties if successful
 *   - `true` if there are no files to process
 *   - `false` if an error occurred during processing
 *
 * @throws {Error} Throws error if options are invalid or processing fails
 *
 * @example Basic usage
 * ```typescript
 * import { createDoc } from '@hrefcl/apidoc';
 *
 * const result = createDoc({
 *   src: ['./src/controllers'],
 *   dest: './docs/api'
 * });
 *
 * if (typeof result !== 'boolean') {
 *   console.log('Generated docs for', result.project.name);
 * }
 * ```
 *
 * @example Advanced configuration
 * ```typescript
 * const result = createDoc({
 *   src: ['./src/api', './src/controllers'],
 *   dest: './public/docs',
 *   name: 'My REST API',
 *   version: '1.2.0',
 *   description: 'A comprehensive REST API for managing resources',
 *   url: 'https://api.example.com/v1',
 *   sampleUrl: 'https://api.example.com/v1',
 *   header: {
 *     title: 'Introduction',
 *     filename: './docs/header.md'
 *   },
 *   footer: {
 *     title: 'Additional Info',
 *     filename: './docs/footer.md'
 *   },
 *   verbose: true,
 *   apiprivate: false
 * });
 * ```
 *
 * @example Error handling
 * ```typescript
 * try {
 *   const result = createDoc({
 *     src: ['./nonexistent'],
 *     dest: './docs'
 *   });
 *
 *   if (result === false) {
 *     console.error('Documentation generation failed');
 *   } else if (result === true) {
 *     console.log('No API documentation found');
 *   } else {
 *     console.log('Success:', result.data.length, 'endpoints documented');
 *   }
 * } catch (error) {
 *   console.error('Configuration error:', error.message);
 * }
 * ```
 *
 * @see {@link https://apidocjs.com} Complete documentation
 * @see {@link https://apidocjs.com/example} Live example
 * @since 4.0.0
 * @public
 */
function createDoc(options) {
    // process options
    try {
        app.options = optionsProcessor.process(options);
    }
    catch (e) {
        console.error(e.message);
        process.exit(1);
    }
    // get the default logger
    app.log = defaults.getLogger(app.options);
    // if --warn-error was passed, treat warnings as error and exit with error code
    if (options.warnError) {
        app.log.warn = (msg) => {
            app.log.error(msg);
            process.exit(1);
        };
    }
    // get the markdown parser
    app.markdownParser = defaults.getMarkdownParser(app.options) || {};
    // make sure input is an array
    if (typeof app.options.src === 'string') {
        app.log.warn('Provided "src" option is not an array. Converting it to array.');
        app.options.src = [app.options.src];
    }
    try {
        // generator information
        core.setGeneratorInfos({
            name: pkgJson.name,
            time: new Date().toString(),
            url: pkgJson.homepage || '',
            version: pkgJson.version,
        });
        core.setLogger(app.log);
        core.setMarkdownParser(app.markdownParser);
        const reader = new reader_1.Reader(app);
        core.setPackageInfos(reader.read());
        // this is holding our results from parsing the source code
        const api = core.parse(app.options);
        if (api === true) {
            app.log.info('Nothing to do.');
            return true;
        }
        if (api === false) {
            app.log.error('Error during source code parsing!');
            return false;
        }
        const writer = new writer_1.default(api, app);
        writer.write().then(() => app.log.verbose('All done :)'));
        // Parse the JSON strings back to objects for proper typing
        const parsedData = JSON.parse(api.data);
        const parsedProject = JSON.parse(api.project);
        return {
            data: parsedData,
            project: parsedProject,
        };
    }
    catch (e) {
        app.log.error(e.message);
        if (e.stack) {
            app.log.debug(e.stack);
        }
        return false;
    }
}
// For CommonJS compatibility
module.exports = {
    createDoc,
};
//# sourceMappingURL=index.js.map