// Copyright (c) 2022, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

import fs from 'node:fs';
import path from 'node:path';

import type {ParsedAsmResult} from '../../types/asmresult/asmresult.interfaces.js';
import {CompilerInfo} from '../../types/compiler.interfaces.js';
import type {TypicalExecutionFunc, UnprocessedExecResult} from '../../types/execution/execution.interfaces.js';
import type {ParseFiltersAndOutputOptions} from '../../types/features/filters.interfaces.js';
import {CompilationEnvironment} from '../compilation-env.js';
import {logger} from '../logger.js';
import {maskRootdir} from '../utils.js';
import {IExternalParser} from './external-parser.interface.js';

const starterScriptName = 'dump-and-parse.sh';

export class ExternalParserBase implements IExternalParser {
    private readonly objdumperPath: string;
    private readonly parserPath: string;
    private readonly execFunc: TypicalExecutionFunc;
    private compilerInfo: CompilerInfo;
    private envInfo;

    constructor(compilerInfo: CompilerInfo, envInfo: CompilationEnvironment, execFunc: TypicalExecutionFunc) {
        this.compilerInfo = compilerInfo;
        this.envInfo = envInfo;
        this.objdumperPath = compilerInfo.objdumper;
        this.parserPath = compilerInfo.externalparser.exe;
        if (!fs.existsSync(this.parserPath)) {
            const msg = `External parser for compiler ${compilerInfo.id} does not exist: "${this.parserPath}"`;
            logger.error(msg);
            // Delay exit to allow async log transports (e.g., Loki) to flush
            setTimeout(() => process.exit(1), 5000);
            throw new Error(msg);
        }
        this.execFunc = execFunc;
    }

    private getParserArguments(filters: ParseFiltersAndOutputOptions, fromStdin: boolean): string[] {
        const parameters = ['-plt'];

        if (fromStdin) parameters.push('-stdin');
        if (filters.binary) parameters.push('-binary');
        if (filters.binaryObject) parameters.push('-binary');
        if (filters.labels) parameters.push('-unused_labels');
        if (filters.directives) parameters.push('-directives');
        if (filters.commentOnly) parameters.push('-comment_only');
        if (filters.trim) parameters.push('-whitespace');
        if (filters.libraryCode) parameters.push('-library_functions');
        if (filters.dontMaskFilenames) parameters.push('-dont_mask_filenames');
        if (filters.debugCalls) parameters.push('-debug_calls');

        return parameters;
    }

    private getObjdumpStarterScriptContent(filters: ParseFiltersAndOutputOptions) {
        const parserArgs = this.getParserArguments(filters, true);

        return (
            '#!/bin/bash\n' +
            `OBJDUMP=${this.objdumperPath}\n` +
            `ASMPARSER=${this.parserPath}\n` +
            `$OBJDUMP "$@" | $ASMPARSER ${parserArgs.join(' ')}\n`
        );
    }

    private async writeStarterScriptObjdump(
        buildfolder: string,
        filters: ParseFiltersAndOutputOptions,
    ): Promise<string> {
        const scriptFilepath = path.join(buildfolder, starterScriptName);

        return new Promise(resolve => {
            fs.writeFile(
                scriptFilepath,
                this.getObjdumpStarterScriptContent(filters),
                {
                    encoding: 'utf8',
                    mode: 0o777,
                },
                () => {
                    resolve(maskRootdir(scriptFilepath));
                },
            );
        });
    }

    private parseAsmExecResult(execResult: UnprocessedExecResult): ParsedAsmResult {
        if (execResult.code !== 0) {
            throw new Error(`Internal error running asm parser: ${execResult.stdout}\n${execResult.stderr}`);
        }
        const result = Object.assign({}, execResult, JSON.parse(execResult.stdout));
        delete result.stdout;
        delete result.stderr;
        result.externalParserUsed = true;
        return result;
    }

    public async objdumpAndParseAssembly(
        buildfolder: string,
        objdumpArgs: string[],
        filters: ParseFiltersAndOutputOptions,
    ): Promise<ParsedAsmResult> {
        objdumpArgs = objdumpArgs.map(v => {
            return maskRootdir(v);
        });
        await this.writeStarterScriptObjdump(buildfolder, filters);
        const execOptions = {
            env: this.envInfo.getEnv(this.compilerInfo.needsMulti),
            customCwd: buildfolder,
            maxOutput: 1024 * 1024 * 1024,
        };
        const execResult = await this.execFunc(`./${starterScriptName}`, objdumpArgs, execOptions);
        return this.parseAsmExecResult(execResult);
    }

    public async parseAssembly(filepath: string, filters: ParseFiltersAndOutputOptions): Promise<ParsedAsmResult> {
        const execOptions = {
            env: this.envInfo.getEnv(this.compilerInfo.needsMulti),
        };

        const parserArgs = this.getParserArguments(filters, false);
        parserArgs.push(filepath);

        const execResult = await this.execFunc(this.parserPath, parserArgs, execOptions);
        return this.parseAsmExecResult(execResult);
    }
}
