// SPDX-License-Identifier: GPL-3.0-or-later
/*
 * main.c - The GNUtrition graphical user interface
 *
 * Copyright (C) 2026 Free Software Foundation, Inc.
 *
 * Author: Jason Self <jself@gnu.org>
 *         Anton McClure <asm@gnu.org>
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "budget.h"
#include "db.h"
#include "gui.h"
#include "log.h"
#include "i18n.h"

#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <glib.h>
#include <glib/gstdio.h>

#define PROGRAM_NAME "gnutrition"

/* Get the path to the user's log database.  Uses
   $XDG_DATA_HOME/gnutrition/log.db or ~/.local/share/gnutrition/log.db.
   Returns a dynamically-allocated string.  */
static char *
get_log_path (void)
{
  return g_build_filename (g_get_user_data_dir (), "gnutrition", "log.db", NULL);
}

/* Ensure the directory containing PATH exists.  */
static int
ensure_dir (const char *path)
{
  char *dir = g_path_get_dirname (path);
  int res = g_mkdir_with_parents (dir, 0755);
  g_free (dir);

  if (res < 0)
    {
      fprintf (stderr, _("%s: cannot create directory\n"), PROGRAM_NAME);
      return -1;
    }
  return 0;
}

int
main (int argc, char **argv)
{
  const char *db_path;
  char *log_path;
  sqlite3 *food_db;
  sqlite3 *log_db;
  int calories;
  int exit_status;

  setlocale (LC_ALL, "");
  bindtextdomain ("gnutrition", LOCALEDIR);
  textdomain ("gnutrition");

  static char food_db_full_path[1024];
  snprintf(food_db_full_path, sizeof(food_db_full_path), "%s/food.db", GNUTRITION_DATADIR);
  db_path = food_db_full_path;

  calories = 2000;

  /* Open the food database.  */
  food_db = db_open (db_path);
  if (!food_db)
    return 1;

  /* Open the user's log database.  */
  log_path = get_log_path ();
  if (!log_path)
    {
      db_close (food_db);
      return 1;
    }

  if (ensure_dir (log_path) < 0)
    {
      db_close (food_db);
      free (log_path);
      return 1;
    }

  log_db = log_open (log_path);
  if (!log_db)
    {
      db_close (food_db);
      free (log_path);
      return 1;
    }

  /* Load saved profile calorie target if available.  */
  {
    struct user_profile saved;
    int rc = log_get_profile (log_db, &saved);
    if (rc == 0 && saved.calorie_target > 0)
      calories = saved.calorie_target;
    log_profile_free(&saved);
  }
  exit_status = gui_run (food_db, log_db, calories, argc, argv);

  log_close (log_db);
  db_close (food_db);
  free (log_path);

  return exit_status;
}
