#include "lumacs/editor_core.hpp"
#include "lumacs/tui_editor.hpp"
#include "lumacs/gtk_editor.hpp"
#include "lumacs/logger.hpp"
#include "lumacs/lua_api.hpp" // Added for load_init_file
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <spdlog/spdlog.h>

using namespace lumacs;

void print_help() {
    std::cout << "Usage: lumacs [options] [file]\n"
              << "Options:\n"
              << "  -nw, --no-window   Run in terminal mode (TUI)\n"
              << "  --help             Show this help message\n";
}

int main(int argc, char* argv[]) {
    // Initialize Logger
    Logger::init();
    spdlog::info("Lumacs starting up...");

    bool force_tui = false;
    std::string filename;

    // Parse arguments
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        if (arg == "-nw" || arg == "--no-window") {
            force_tui = true;
        } else if (arg == "--help") {
            print_help();
            return 0;
        } else {
            // Assume it's a filename
            if (filename.empty()) {
                filename = arg;
            }
        }
    }

    try {
        // Initialize Core
        EditorCore core;

        // Select Frontend
        std::unique_ptr<IEditorView> view;

#ifdef LUMACS_WITH_GTK
        if (!force_tui) {
            view = create_gtk_editor();
        }
#endif

        // Fallback to TUI if GTK not available or TUI forced
        if (!view) {
            if (!force_tui && !view) {
                // If we tried to load GTK and failed (e.g. create_gtk_editor returned null), warn user?
                // For now, create_gtk_editor prints to stderr if built without GTK.
                spdlog::warn("GTK frontend requested but not available/loaded. Falling back to TUI.");
            }
            view = create_tui_editor();
        }

        if (!view) {
            spdlog::critical("Failed to create editor interface.");
            return 1;
        }

        // Link Core and View
        view->set_core(&core);
        core.on_event([&view](EditorEvent event) {
            view->handle_editor_event(event);
        });

        // Initialize View
        view->init();

        // Load Lua configuration (Embedded Defaults + User Init)
        if (core.lua_api()) {
            core.lua_api()->load_init_file();
        }

        // Load initial file if provided
        if (!filename.empty()) {
            core.load_file(filename);
        }

        // Run main loop
        view->run();

        // Clear event callbacks before view is destroyed to prevent use-after-free
        core.clear_event_callbacks();

    } catch (const std::exception& e) {
        spdlog::critical("Fatal Error: {}", e.what());
        return 1;
    }

    return 0;
}
