#include <gtkmm/application.h>
#include "DatabaseManager.hpp"
#include "BookList.hpp"
#include "BibliothecaWindow.hpp"
#include <giomm/file.h>
#include <giomm/error.h>
#include <iostream>

static std::string ensureDataDir() {
  auto dir = Glib::build_filename(Glib::get_user_data_dir(), "bibliotheca");
  auto f   = Gio::File::create_for_path(dir);

  // If it exists but isn’t a directory, that’s a real error.
  try {
    auto type = f->query_file_type(); // Gio::FileType
    if (type == Gio::FileType::DIRECTORY) return dir;
    if (type != Gio::FileType::UNKNOWN) {
      throw std::runtime_error("Path exists but is not a directory: " + dir);
    }
  } catch (const Gio::Error&) {
    // query_file_type() may throw if it doesn't exist—ignore and proceed to create
  }

  // Create the directory; ignore “already exists”.
  try {
    f->make_directory_with_parents();
  } catch (const Gio::Error& e) {
    if (e.code() != Gio::Error::EXISTS) {
      std::cerr << "Failed to create data dir: " << e.what() << "\n";
      throw; // or pick a fallback path
    }
  }
  return dir;
}

int main(int argc, char** argv) {
  auto app = Gtk::Application::create("eu.bernardomagri.bibliotheca");

  const auto dataDir = ensureDataDir();
  const auto dbPath  = Glib::build_filename(dataDir, "bibliotheca.sqlite");

  DatabaseManager db{dbPath};
  BookList bookList{db};
  bookList.loadAll();

  return app->make_window_and_run<BibliothecaWindow>(argc, argv, db, bookList);
}
