#include "core/profile.h"
#include "extensions/adblock/adblock.h"
#include "extensions/adblock/yt_adblock.h"
#include "settings/flags.h"
#include "ui/window.h"
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>

static Profile *global_profile = NULL;
static AdblockManager *global_adblock_manager = NULL;
static YTAdblockManager *global_yt_adblock_manager = NULL;
static FlagsManager *global_flags_manager = NULL;

static void on_filter_loaded(AdblockManager *manager, gboolean success,
                             GError *error, gpointer user_data) {
  if (success) {
    g_print("✓ Adblock filter loaded successfully!\n");
    g_print("  Total filters loaded: %u\n",
            adblock_manager_get_filter_count(manager));
  } else {
    g_warning("✗ Failed to load adblock filter: %s\n",
              error ? error->message : "Unknown error");
  }
}

static void activate(GtkApplication *app, gpointer user_data) {
  // Initialize profile if not already done
  if (!global_profile) {
    global_profile = init_default_profile();
    if (!global_profile) {
      g_printerr("Failed to initialize default profile\n");
      return;
    }
  }

  // Initialize flags manager and apply environment variables BEFORE creating
  // WebViews
  if (!global_flags_manager) {
    g_print("Initializing flags manager...\n");
    global_flags_manager = flags_manager_new(global_profile);
    if (global_flags_manager) {
      flags_manager_apply_all(global_flags_manager);
    } else {
      g_warning("Failed to create flags manager\n");
    }
  }

  g_print("Creating window...\n");

  // Initialize adblock manager
  if (!global_adblock_manager) {
    g_print("Initializing adblock...\n");
    global_adblock_manager = adblock_manager_new(NULL);

    if (global_adblock_manager) {
      // Load EasyList filter
      GError *error = NULL;
      const gchar *filter_path = "src/extensions/adblock/easylist.txt";

      gboolean started = adblock_manager_load_from_file(
          global_adblock_manager, filter_path, "easylist", on_filter_loaded,
          NULL, &error);

      if (!started) {
        g_warning("Failed to start loading adblock filter: %s",
                  error ? error->message : "Unknown error");
        if (error) {
          g_error_free(error);
        }
      }
    } else {
      g_warning("Failed to create adblock manager");
    }
  }

  // Initialize YouTube adblock manager
  if (!global_yt_adblock_manager) {
    g_print("Initializing YouTube adblock...\n");
    global_yt_adblock_manager = yt_adblock_manager_new();

    if (!global_yt_adblock_manager) {
      g_warning("Failed to create YouTube adblock manager");
    }
  }

  create_window(app, global_profile);
  g_print("Window created. Starting main loop...\n");
}

static void on_shutdown(GtkApplication *app, gpointer user_data) {
  // Cleanup adblock
  if (global_adblock_manager) {
    adblock_manager_free(global_adblock_manager);
    global_adblock_manager = NULL;
  }

  // Cleanup YouTube adblock
  if (global_yt_adblock_manager) {
    yt_adblock_manager_free(global_yt_adblock_manager);
    global_yt_adblock_manager = NULL;
  }

  // Cleanup flags manager
  if (global_flags_manager) {
    flags_manager_free(global_flags_manager);
    global_flags_manager = NULL;
  }
}

// Make adblock manager accessible to other modules
AdblockManager *get_global_adblock_manager(void) {
  return global_adblock_manager;
}

// Make YouTube adblock manager accessible to other modules
YTAdblockManager *get_global_yt_adblock_manager(void) {
  return global_yt_adblock_manager;
}

// Make flags manager accessible to other modules
FlagsManager *get_global_flags_manager(void) { return global_flags_manager; }

int main(int argc, char **argv) {
  GtkApplication *app;
  int status;

  g_print("Starting LeafWeb...\n");
  gtk_init(&argc, &argv);

  app = gtk_application_new("com.example.leafweb", G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
  g_signal_connect(app, "shutdown", G_CALLBACK(on_shutdown), NULL);
  status = g_application_run(G_APPLICATION(app), argc, argv);
  g_object_unref(app);

  return status;
}
