#' @title Setup twscrapeR
#' @description Checks that Python and the Python `twscrape` package are available and configures the active reticulate session. It does not install Python or Python packages automatically.
#' @param python_path Ruta a Python (opcional, se detecta automaticamente)
#' @param install_python Deprecated compatibility argument. Ignored; installation must be performed by the user outside package functions.
#' @param ask Deprecated compatibility argument. Ignored; retained to avoid breaking existing calls.
#' @return Invisibly returns `TRUE` when Python >= 3.10 and the Python `twscrape` module are available and configured. Invisibly returns `FALSE` otherwise, after printing installation instructions.
#' @export
#' @examples
#' \donttest{
#' if (interactive()) {
#'   setup_twscraper()
#' }
#' }
setup_twscraper <- function(python_path = NULL, install_python = TRUE, ask = TRUE) {
  cli::cli_h1("Configuracion de twscrapeR")
  cli::cli_text("")

  if (!missing(install_python) || !missing(ask)) {
    cli::cli_alert_info("Los argumentos 'install_python' y 'ask' se conservan por compatibilidad, pero ya no instalan software automaticamente.")
  }

  cli::cli_h2("Paso 1: Verificacion de Python")

  python_found <- FALSE

  if (!is.null(python_path)) {
    cli::cli_alert_info("Usando Python especificado: {python_path}")
    if (file.exists(python_path)) {
      reticulate::use_python(python_path, required = TRUE)
      python_found <- TRUE
    } else {
      cli::cli_alert_danger("Python no encontrado en: {python_path}")
    }
  }

  if (!python_found) {
    cli::cli_alert_info("Buscando Python en el sistema...")

    tryCatch({
      reticulate::py_available(initialize = TRUE)
      python_found <- TRUE
      python_path <- reticulate::py_config()$python
      cli::cli_alert_success("Python encontrado: {python_path}")
    }, error = function(e) {
      cli::cli_alert_warning("Python no detectado automaticamente")
    })
  }

  if (python_found) {
    tryCatch({
      py_version <- as.character(reticulate::py_config()$version)
      version_parts <- as.numeric(strsplit(py_version, "\\.")[[1]][1:2])
      python_version_ok <- (version_parts[1] > 3) || (version_parts[1] == 3 && version_parts[2] >= 10)

      if (!python_version_ok) {
        cli::cli_text("")
        cli::cli_alert_warning("Python {py_version} encontrado, pero twscrape requiere Python >= 3.10")
        python_found <- FALSE
      }
    }, error = function(e) {
      cli::cli_alert_warning("No se pudo verificar la version de Python")
      python_found <- FALSE
    })
  }

  if (!python_found) {
    cli::cli_text("")
    cli::cli_alert_warning("Se necesita Python 3.10 o superior")
    cli::cli_text("Instala Python 3.10+ fuera de R y vuelve a ejecutar setup_twscraper().")
    cli::cli_text("Descarga: https://www.python.org/downloads/")
    cli::cli_text("Si usas conda, crea un entorno manualmente, por ejemplo: conda create -n twscraper_env python=3.11")
    return(invisible(FALSE))
  }

  cli::cli_text("")
  cli::cli_h2("Paso 2: Verificacion de twscrape (Python)")

  has_twscrape <- reticulate::py_module_available("twscrape")

  if (!has_twscrape) {
    cli::cli_alert_warning("El modulo Python 'twscrape' no esta instalado en el Python activo")
    cli::cli_text("Instalalo fuera de las funciones del paquete, por ejemplo:")
    cli::cli_code("python -m pip install 'twscrape>=0.18.0'")
    cli::cli_text("Luego vuelve a ejecutar setup_twscraper().")
    return(invisible(FALSE))
  }

  cli::cli_alert_success("twscrape ya esta instalado")

  cli::cli_text("")
  cli::cli_h2("Paso 3: Configuracion final")

  .twscraper_env$python_path <- python_path
  .twscraper_env$twscrape <- reticulate::import("twscrape")
  .twscraper_env$configured <- TRUE

  cli::cli_alert_success("Configuracion completada")
  cli::cli_text("")

  cli::cli_rule("Resumen de Configuracion")
  cli::cli_text("")
  cli::cli_dl(c(
    "Python" = python_path,
    "Version Python" = as.character(reticulate::py_config()$version),
    "twscrape" = "Disponible y listo"
  ))
  cli::cli_text("")

  cli::cli_alert_success("twscrapeR esta listo para usar!")
  cli::cli_text("")

  cli::cli_text("{.strong Proximos pasos:}")
  cli::cli_ol(c(
    "Agregar cuenta: add_account_from_env() o add_account('usuario', 'password', 'email', 'email_pass', cookies='...')",
    "Buscar tweets: search_tweets('query', n = 100)",
    "Ver ayuda: ?twscrapeR"
  ))
  cli::cli_text("")

  return(invisible(TRUE))
}

#' @title Verificar si twscrapeR esta configurado
#' @description Verifica si Python y twscrape estan configurados en la sesion actual.
#' @param ... Ignorado; reservado para compatibilidad futura.
#' @return `TRUE` si twscrapeR esta configurado en la sesion actual; `FALSE` en caso contrario.
#' @export
#' @examples
#' check_setup()
check_setup <- function(...) {
  if (!exists(".twscraper_env") || !.twscraper_env$configured) {
    cli::cli_alert_warning("twscrapeR no esta configurado")
    cli::cli_text("Ejecuta: setup_twscraper()")
    return(FALSE)
  }

  cli::cli_alert_success("twscrapeR esta configurado correctamente")
  cli::cli_dl(c(
    "Python" = .twscraper_env$python_path,
    "twscrape" = "Activo"
  ))
  return(TRUE)
}

#' Entorno global para almacenar configuracion
#' @keywords internal
.twscraper_env <- new.env(parent = emptyenv())
.twscraper_env$configured <- FALSE
.twscraper_env$python_path <- NULL
.twscraper_env$twscrape <- NULL

#' @title Asegurar que twscrapeR esta configurado
#' @description Uso interno - verifica configuracion antes de operaciones
#' @keywords internal
ensure_configured <- function() {
  if (!.twscraper_env$configured) {
    cli::cli_alert_warning("twscrapeR no esta configurado")
    cli::cli_text("Ejecuta setup_twscraper() despues de instalar Python 3.10+ y twscrape>=0.18.0.")
    stop("twscrapeR no esta configurado. Ejecuta setup_twscraper() manualmente.", call. = FALSE)
  }
}
