#include "haze.h"
#include "haze_version.h"
#include "libqbe.h"

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#if defined(_WIN32)
#include <process.h>
#else
#include <sys/wait.h>
#include <unistd.h>
#endif

extern "C" const unsigned char haze_embedded_runtime_archive[];
extern "C" const unsigned long long haze_embedded_runtime_archive_size;

namespace fs = std::filesystem;

namespace {

struct Options {
    std::string input;
    std::string output;
    std::string target;
    std::string cc;
    std::string runtime;
    bool emit_il = false;
    bool emit_asm = false;
    bool emit_obj = false;
    bool run = false;
    bool keep = false;
    bool verbose = false;
    bool dynamic = false;
    bool release = false;
    bool format_write = false;
    bool format_check = false;
};

void usage(FILE* f) {
    std::fprintf(f, "usage: hz [options] file.hz\n"
                    "\n"
                    "  -o file       output path\n"
                    "  -target name  UQBE target (amd64_sysv, amd64_apple, amd64_win,\n"
                    "                arm64, arm64_apple, arm64_win, rv64)\n"
                    "  -S            stop after assembly\n"
                    "  -c            stop after object file\n"
                    "  -qbe          stop after QBE IL\n"
                    "  -run          run the produced executable\n"
                    "  -d            link dynamically (default is static)\n"
                    "  -release      omit runtime contract and invariant checks\n"
                    "  -w            write formatted output back to the file\n"
                    "  -check        fail if the file is not formatted\n"
                    "  -keep         keep temporary files\n"
                    "  -cc path      C compiler used for assembly/linking\n"
                    "  -runtime path path to libhazert.a\n"
                    "  -v            print version\n"
                    "  -h            print this help\n"
                    "\n"
                    "subcommands:\n"
                    "  hz fmt file.hz   pretty-print a source file\n"
                    "  hz lsp           run the language server on stdio\n");
}

std::string lower(std::string s) {
    for (char& c : s)
        c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    return s;
}

std::string canonical_target(std::string name) {
    name = lower(std::move(name));
    if (name == "amd64_sysv" || name == "amd64_apple" || name == "amd64_win" || name == "arm64" ||
        name == "arm64_apple" || name == "arm64_win" || name == "rv64")
        return name;
    if (name == "linux/amd64" || name == "freebsd/amd64" || name == "openbsd/amd64" ||
        name == "netbsd/amd64" || name == "dragonfly/amd64")
        return "amd64_sysv";
    if (name == "linux/arm64" || name == "freebsd/arm64" || name == "openbsd/arm64" ||
        name == "netbsd/arm64")
        return "arm64";
    if (name == "linux/riscv64")
        return "rv64";
    if (name == "darwin/amd64" || name == "macos/amd64" || name == "macosx/amd64")
        return "amd64_apple";
    if (name == "darwin/arm64" || name == "macos/arm64" || name == "macosx/arm64")
        return "arm64_apple";
    if (name == "windows/amd64" || name == "win/amd64")
        return "amd64_win";
    if (name == "windows/arm64" || name == "win/arm64")
        return "arm64_win";
    return name;
}

std::string read_file(const fs::path& p) {
    std::ifstream in(p, std::ios::binary);
    if (!in)
        throw std::runtime_error("cannot read '" + p.string() + "'");
    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}

void write_file(const fs::path& p, const std::string& s) {
    std::ofstream out(p, std::ios::binary);
    if (!out)
        throw std::runtime_error("cannot write '" + p.string() + "'");
    out << s;
}

void write_embedded_runtime(const fs::path& p) {
    std::ofstream out(p, std::ios::binary);
    if (!out)
        throw std::runtime_error("cannot write '" + p.string() + "'");
    out.write(reinterpret_cast<const char*>(haze_embedded_runtime_archive),
              static_cast<std::streamsize>(haze_embedded_runtime_archive_size));
    if (!out)
        throw std::runtime_error("cannot write '" + p.string() + "'");
}

std::string shell_quote(const std::string& s) {
#if defined(_WIN32)
    std::string out = "\"";
    for (char c : s) {
        if (c == '"')
            out += "\\\"";
        else
            out.push_back(c);
    }
    out += "\"";
    return out;
#else
    std::string out = "'";
    for (char c : s) {
        if (c == '\'')
            out += "'\\''";
        else
            out.push_back(c);
    }
    out += "'";
    return out;
#endif
}

int run_tool(const std::vector<std::string>& argv, bool verbose) {
    std::ostringstream cmd;
    for (size_t i = 0; i < argv.size(); i++) {
        if (i)
            cmd << ' ';
        cmd << shell_quote(argv[i]);
    }
    if (verbose)
        std::fprintf(stderr, "+ %s\n", cmd.str().c_str());
    int rc = std::system(cmd.str().c_str());
#if defined(_WIN32)
    return rc;
#else
    if (rc == -1)
        return 1;
    if (WIFEXITED(rc))
        return WEXITSTATUS(rc);
    return 1;
#endif
}

bool is_executable_file(const fs::path& p) {
    std::error_code ec;
    return fs::is_regular_file(p, ec);
}

std::string find_in_path(const std::string& name) {
    fs::path direct(name);
    if (direct.has_parent_path()) {
        std::error_code ec;
        if (fs::is_regular_file(direct, ec))
            return fs::absolute(direct).string();
        return {};
    }
    const char* path = std::getenv("PATH");
    if (!path)
        return {};
#if defined(_WIN32)
    char sep = ';';
#else
    char sep = ':';
#endif
    std::string all(path);
    size_t start = 0;
    while (start <= all.size()) {
        size_t end = all.find(sep, start);
        if (end == std::string::npos)
            end = all.size();
        fs::path dir = all.substr(start, end - start);
        if (!dir.empty()) {
            fs::path cand = dir / name;
            if (is_executable_file(cand))
                return cand.string();
#if defined(_WIN32)
            cand = dir / (name + ".exe");
            if (is_executable_file(cand))
                return cand.string();
#endif
        }
        if (end == all.size())
            break;
        start = end + 1;
    }
    return {};
}

fs::path executable_dir(const char* argv0) {
    std::error_code ec;
    fs::path p = argv0 && *argv0 ? fs::path(argv0) : fs::path("hz");
    if (!p.has_parent_path()) {
        std::string found = find_in_path(p.string());
        if (!found.empty())
            p = found;
    }
    p = fs::absolute(p, ec);
    if (ec)
        p = fs::path(argv0 ? argv0 : "hz");
    p = fs::weakly_canonical(p, ec);
    return p.parent_path();
}

std::string find_runtime(const Options& o, const fs::path& exe_dir, const fs::path& tmp) {
    if (!o.runtime.empty()) {
        if (!is_executable_file(o.runtime))
            throw std::runtime_error("runtime archive not found: " + o.runtime);
        return fs::absolute(o.runtime).string();
    }
    if (const char* env = std::getenv("HAZE_RUNTIME")) {
        if (*env && is_executable_file(env))
            return fs::absolute(env).string();
    }
    std::vector<fs::path> dirs = {exe_dir, exe_dir / ".." / "lib", exe_dir / ".." / "lib" / "haze",
                                  fs::current_path()};
    const char* names[] = {"libhazert.a", "hazert.lib", "libhazert.lib", "hazert.o"};
    for (auto& d : dirs) {
        for (const char* n : names) {
            fs::path p = d / n;
            std::error_code ec;
            if (fs::is_regular_file(p, ec))
                return fs::weakly_canonical(p, ec).string();
        }
    }

    fs::path embedded = tmp / "libhazert.a";
    write_embedded_runtime(embedded);
    return embedded.string();
}

std::string find_cc(const Options& o) {
    if (!o.cc.empty()) {
        std::string p = find_in_path(o.cc);
        if (p.empty())
            throw std::runtime_error("C compiler not found: " + o.cc);
        return p;
    }
    if (const char* env = std::getenv("HAZE_CC")) {
        if (*env) {
            std::string p = find_in_path(env);
            if (!p.empty())
                return p;
        }
    }
    if (const char* env = std::getenv("CC")) {
        if (*env) {
            std::string p = find_in_path(env);
            if (!p.empty())
                return p;
        }
    }
    const char* tries[] = {
#if defined(_WIN32)
        "clang", "gcc", "cc", "cl"
#else
        "cc", "clang", "gcc"
#endif
    };
    for (const char* t : tries) {
        std::string p = find_in_path(t);
        if (!p.empty())
            return p;
    }
    throw std::runtime_error("no C compiler found; pass -cc path");
}

std::string default_output(const std::string& input, const char* ext) {
    fs::path p(input);
    p.replace_extension(ext);
    return p.string();
}

#if defined(_WIN32)
unsigned long process_id() {
    return static_cast<unsigned long>(_getpid());
}
#else
unsigned long process_id() {
    return static_cast<unsigned long>(getpid());
}
#endif

fs::path make_temp_dir() {
    std::error_code ec;
    fs::path base = fs::temp_directory_path(ec);
    if (ec)
        base = fs::current_path();
    base /= "haze";
    fs::create_directories(base, ec);
    for (int i = 0; i < 1000; i++) {
        fs::path p = base / ("work-" + std::to_string(process_id()) + "-" + std::to_string(i));
        if (fs::create_directory(p, ec))
            return p;
    }
    throw std::runtime_error("cannot create temporary directory");
}

std::string format_error(const std::string& file, const haze::Error& e) {
    std::ostringstream ss;
    ss << file << ':' << e.pos.line << ':' << e.pos.col << ": error: " << e.what();
    return ss.str();
}

} // namespace

int main(int argc, char** argv) {
    Options opt;
    std::vector<std::string> positional;

    for (int i = 1; i < argc; i++) {
        std::string a = argv[i];
        if (a == "-h") {
            usage(stdout);
            return 0;
        }
        if (a == "-v") {
            std::printf("haze v%s", HAZE_VERSION);
            if (HAZE_VEINS_HASH[0])
                std::printf(" %s", HAZE_VEINS_HASH);
            std::printf(" (uqbe target %s)\n", qbe_default_target());
            return 0;
        }
        if (a == "-S") {
            opt.emit_asm = true;
            continue;
        }
        if (a == "-c") {
            opt.emit_obj = true;
            continue;
        }
        if (a == "-qbe") {
            opt.emit_il = true;
            continue;
        }
        if (a == "-run") {
            opt.run = true;
            continue;
        }
        if (a == "-d") {
            opt.dynamic = true;
            continue;
        }
        if (a == "-release") {
            opt.release = true;
            continue;
        }
        if (a == "-keep") {
            opt.keep = true;
            continue;
        }
        if (a == "-w") {
            opt.format_write = true;
            continue;
        }
        if (a == "-check") {
            opt.format_check = true;
            continue;
        }
        if (a == "-verbose") {
            opt.verbose = true;
            continue;
        }
        if (a == "-o" || a == "-target" || a == "-cc" || a == "-runtime") {
            if (i + 1 >= argc) {
                std::fprintf(stderr, "hz: missing value after %s\n", a.c_str());
                return 1;
            }
            std::string v = argv[++i];
            if (a == "-o")
                opt.output = v;
            else if (a == "-target")
                opt.target = v;
            else if (a == "-cc")
                opt.cc = v;
            else
                opt.runtime = v;
            continue;
        }
        if (a.size() > 2 && a[0] == '-' && a[1] == 'o')
            opt.output = a.substr(2);
        else if (a.size() > 7 && a.substr(0, 7) == "-target")
            opt.target = a.substr(7);
        else if (a.size() > 3 && a.substr(0, 3) == "-cc")
            opt.cc = a.substr(3);
        else if (a.size() > 8 && a.substr(0, 8) == "-runtime")
            opt.runtime = a.substr(8);
        else if (!a.empty() && a[0] == '-') {
            if (a.size() > 1 && a[1] == '-') {
                std::fprintf(stderr,
                             "hz: GNU-style flag '%s' rejected; use single-dash "
                             "Plan 9 flags such as -target\n",
                             a.c_str());
                return 1;
            }
            std::fprintf(stderr, "hz: unknown flag '%s' (try -h)\n", a.c_str());
            return 1;
        } else {
            positional.push_back(a);
        }
    }

    if (!positional.empty()) {
        const std::string& first = positional.front();
        if (first == "lsp") {
            if (positional.size() != 1) {
                std::fprintf(stderr, "hz: lsp takes no arguments\n");
                return 2;
            }
            haze::run_lsp_server();
            return 0;
        }
        if (first == "fmt") {
            if (positional.size() != 2) {
                std::fprintf(stderr, "hz: fmt expects one .hz file\n");
                return 2;
            }
            try {
                fs::path path(positional[1]);
                if (!fs::is_regular_file(path))
                    throw std::runtime_error("input file not found: " + path.string());
                std::string source = read_file(path);
                std::string formatted = haze::format_source(source);
                if (opt.format_check) {
                    if (formatted != source) {
                        std::fprintf(stderr, "hz: %s is not formatted\n", path.string().c_str());
                        return 1;
                    }
                    return 0;
                }
                if (opt.format_write)
                    write_file(path, formatted);
                else
                    std::fwrite(formatted.data(), 1, formatted.size(), stdout);
                return 0;
            } catch (const std::exception& e) {
                std::fprintf(stderr, "hz: %s\n", e.what());
                return 1;
            }
        }
        if (first == "build" || first == "check" || first == "run" || first == "qbe" ||
            first == "asm" || first == "compile") {
            if (first == "run")
                opt.run = true;
            if (first == "qbe")
                opt.emit_il = true;
            if (first == "asm")
                opt.emit_asm = true;
            positional.erase(positional.begin());
        }
    }

    if (positional.size() != 1) {
        usage(stderr);
        return 2;
    }
    opt.input = positional[0];

    try {
        fs::path input(opt.input);
        if (!fs::is_regular_file(input))
            throw std::runtime_error("input file not found: " + opt.input);
        if (lower(input.extension().string()) != ".hz")
            throw std::runtime_error("hz expects a .hz source file");

        std::string target =
            opt.target.empty() ? qbe_default_target() : canonical_target(opt.target);
        if (!qbe_target_supported(target.c_str()))
            throw std::runtime_error("unknown target '" + target +
                                     "'; supported: " + qbe_target_list());

        haze::set_compile_target(haze::target_for_qbe(target));

        haze::Program program = haze::load_program(input.string());
        program.release = opt.release;
        haze::check_program(program);
        std::string il = haze::generate_qbe(program, input.filename().string());

        if (opt.emit_il) {
            std::string out = opt.output.empty() ? default_output(opt.input, ".ssa") : opt.output;
            if (out == "-")
                std::fwrite(il.data(), 1, il.size(), stdout);
            else {
                write_file(out, il);
                if (opt.verbose)
                    std::fprintf(stderr, "hz: wrote %s\n", out.c_str());
            }
            return 0;
        }

        fs::path tmp = make_temp_dir();
        fs::path ilpath = tmp / "unit.ssa";
        fs::path asmpath = tmp / "unit.s";
        write_file(ilpath, il);

        if (qbe_compile_file(ilpath.string().c_str(), asmpath.string().c_str(), target.c_str()) !=
            0)
            throw std::runtime_error("UQBE failed to compile the generated IL");

        if (opt.emit_asm) {
            std::string out = opt.output.empty() ? default_output(opt.input, ".s") : opt.output;
            if (out == "-")
                std::fputs(read_file(asmpath).c_str(), stdout);
            else
                fs::copy_file(asmpath, out, fs::copy_options::overwrite_existing);
            if (opt.keep)
                std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());
            else
                fs::remove_all(tmp);
            return 0;
        }

        std::string cc = find_cc(opt);
        fs::path exe_dir = executable_dir(argv[0]);
        std::string runtime = find_runtime(opt, exe_dir, tmp);

        if (opt.emit_obj) {
            std::string out = opt.output.empty() ? default_output(opt.input, ".o") : opt.output;
            std::vector<std::string> cmd = {cc, "-c", asmpath.string(), "-o", out};
            int rc = run_tool(cmd, opt.verbose);
            if (rc != 0)
                throw std::runtime_error("assembler failed");
            if (opt.keep)
                std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());
            else
                fs::remove_all(tmp);
            return 0;
        }

        std::string out = opt.output;
        if (out.empty()) {
            out = default_output(opt.input, "");
#if defined(_WIN32)
            if (fs::path(out).extension().empty())
                out += ".exe";
#endif
        }

        std::vector<std::string> cmd = {cc};
#if !defined(_WIN32)
        if (!opt.dynamic)
            cmd.push_back("-static");
        cmd.push_back("-pthread");
#endif
        cmd.push_back(asmpath.string());
        cmd.push_back(runtime);
        cmd.push_back("-o");
        cmd.push_back(out);
        int rc = run_tool(cmd, opt.verbose);
        if (rc != 0)
            throw std::runtime_error("linker failed");

        if (opt.keep)
            std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());
        else
            fs::remove_all(tmp);

        if (opt.run) {
            std::string runpath = out;
#if !defined(_WIN32)
            if (runpath.find('/') == std::string::npos)
                runpath = "./" + runpath;
#endif
            return run_tool({runpath}, opt.verbose);
        }
        return 0;
    } catch (const haze::Error& e) {
        std::fprintf(stderr, "%s\n", format_error(opt.input, e).c_str());
        return 1;
    } catch (const std::exception& e) {
        std::fprintf(stderr, "hz: %s\n", e.what());
        return 1;
    }
}
