/* ************************************************************************
 * Copyright (C) 2025-2026 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * ************************************************************************ */

#include <iostream>  // fixme: don't use iostream.
#include <string>

#include "gfx/GpuArchManager.hpp"

namespace stinkytofu {
bool genAllArchRocisaMappings(GpuArchManager& manager, const std::string& outdir);
bool genLogicalToAsmMappings(GpuArchManager& manager, const std::string& outdir);
bool genPeepholePatterns(const std::string& patternFile, const std::string& outdir);
bool genLogicalIR(const std::string& outdir);
bool genInstructions(const std::string& arch, const std::string& inputDir,
                     const std::string& outputDir);
}  // namespace stinkytofu

using namespace stinkytofu;

static void usage() {
    std::cout
        << "Usage: tablegen <outdir> <hardwareDir>\n"
        << "       tablegen --gen-instructions --arch=<gfx> --input-dir=<dir> --output-dir=<dir>\n"
        << "\n"
        << "Mode 1 (default):\n"
        << "  outdir: The directory to output the generated files.\n"
        << "  hardwareDir: The directory to the hardware data.\n"
        << "\n"
        << "Mode 2 (instruction generation):\n"
        << "  --gen-instructions: Generate instruction metadata from .def files\n"
        << "  --arch=<gfx>: Architecture (e.g. gfx1250); normalized to GfxXXX for "
           ".def filenames\n"
        << "  --input-dir=<dir>: Input directory containing .def files\n"
        << "  --output-dir=<dir>: Output directory for generated .inc files\n"
        << "\n"
        << "Examples:\n"
        << "  tablegen out shared/stinkytofu/hardware\n"
        << "  tablegen --gen-instructions --arch=gfx1250 --input-dir=hardware/src/gfx "
           "--output-dir=hardware/generated\n";
}

int main(int argc, char** argv) {
    constexpr int SUCCESS = 0;
    constexpr int FAILURE = 1;

    // Check for --gen-instructions mode
    if (argc > 1 && std::string(argv[1]) == "--gen-instructions") {
        // Parse arguments
        std::string arch;
        std::string inputDir;
        std::string outputDir;

        for (int i = 2; i < argc; ++i) {
            std::string arg = argv[i];
            if (arg.starts_with("--arch="))
                arch = arg.substr(7);
            else if (arg.starts_with("--input-dir="))
                inputDir = arg.substr(12);
            else if (arg.starts_with("--output-dir="))
                outputDir = arg.substr(13);
        }

        if (arch.empty() || inputDir.empty() || outputDir.empty()) {
            std::cerr << "Error: Missing required arguments for --gen-instructions\n\n";
            usage();
            return FAILURE;
        }

        bool success = genInstructions(arch, inputDir, outputDir);
        return success ? SUCCESS : FAILURE;
    }

    // Default mode
    if (argc < 3) {
        usage();
        return FAILURE;
    }
    std::string outdir = argv[1];
    std::string hardwareDir = argv[2];

    bool success = true;

    GpuArchManager manager;

    success &= GpuArchManager::initAllArchs(manager);

    if (!success) {
        std::cerr << "Failed to initialize all architectures\n";
        return FAILURE;
    }

    // ISA .inc are generated by tablegen_inst_gen (instruction_generated), not here.
    success &= genAllArchRocisaMappings(manager, outdir);
    success &= genLogicalToAsmMappings(manager, outdir);

    // Generate peephole optimization patterns (assembly IR)
    std::string asmPatternFile = hardwareDir + "/../src/transforms/asm/PeepholePatterns.pattern";
    success &= genPeepholePatterns(asmPatternFile, outdir);

    // Generate high-level IR optimization patterns
    std::string hlirPatternFile =
        hardwareDir + "/../src/transforms/logical/LogicalIRPatterns.pattern";
    success &= genPeepholePatterns(hlirPatternFile, outdir);

    // Generate high-level IR instruction classes and mappings
    success &= genLogicalIR(outdir);

    return success ? SUCCESS : FAILURE;
}
