# Helper for default values, handles NULL and single NA
`%||%` <- function(x, y) {
  if (is.null(x) || (length(x) == 1 && is.na(x))) y else x
}

# Attempt to get package metadata
pkg_meta_athlytics <- NULL

# Try using utils::packageDescription first
# Suppress warnings because a warning is given if package not found, but it still returns NA
temp_desc <- suppressWarnings(try(utils::packageDescription("Athlytics"), silent = TRUE))
if (is.list(temp_desc) && !inherits(temp_desc, "try-error")) {
    pkg_meta_athlytics <- temp_desc
}

# If packageDescription failed or didn't return a list, try reading DESCRIPTION directly
if (is.null(pkg_meta_athlytics)) {
    # The CITATION file is in inst/, so DESCRIPTION is ../DESCRIPTION from inst/
    # or directly DESCRIPTION if the working dir is the package root during some checks.
    # Let's try both relative paths for robustness during different check phases.
    desc_file_paths <- c(file.path("..", "DESCRIPTION"), "DESCRIPTION")
    desc_file_found <- NULL
    for (p in desc_file_paths) {
        if (file.exists(p)) {
            desc_file_found <- p
            break
        }
    }

    if (!is.null(desc_file_found)) {
        tryCatch({
            dcf <- read.dcf(desc_file_found)
            fields <- as.list(dcf[1, ]) # Take the first entry
            pkg_meta_athlytics <- list(
                Package     = fields$Package,
                Title       = fields$Title,
                `Authors@R` = fields$`Authors@R`,
                Version     = fields$Version,
                URL         = fields$URL
                # 'Packaged' field is not in DESCRIPTION, will be handled below
            )
        }, error = function(e) {
            # Failed to read/parse DESCRIPTION, pkg_meta_athlytics remains NULL
            # message(paste("Error reading DESCRIPTION:", e$message)) # Optional debug
        })
    }
}

# If still no metadata (all above failed), use hardcoded defaults
if (is.null(pkg_meta_athlytics)) {
    # message("Using hardcoded fallback metadata in CITATION.") # Optional debug
    pkg_meta_athlytics <- list(
        Package     = "Athlytics",
        Title       = "Athlytics: Advanced Sports Performance Analysis", # Generic title
        `Authors@R` = 'person(given = "Zhiang", family = "HE", role = c("aut", "cre"), email = "ang@hezhiang.com")', # Actual author
        Version     = "0.1.2", # Update if version changes, or use placeholder like "0.0.0"
        URL         = "https://github.com/CurryAng/Athlytics"
        # 'Packaged' field will be handled below
    )
}

# Ensure essential fields have defaults and set a 'Packaged' date for year extraction
current_year_text <- format(Sys.Date(), "%Y")
# Use a fixed reference date like package creation or first release if more appropriate
# than Sys.Date() for 'Packaged' if it's missing.
# For now, using current date ensures year extraction works.
default_packaged_date_for_year <- paste0(current_year_text, "-01-01")

pkg_meta_athlytics$Package     <- pkg_meta_athlytics$Package     %||% "Athlytics"
pkg_meta_athlytics$Title       <- pkg_meta_athlytics$Title       %||% "Athlytics Package (Title not found)"
pkg_meta_athlytics$`Authors@R` <- pkg_meta_athlytics$`Authors@R` %||% 'person(given="Unknown", family="Author")'
pkg_meta_athlytics$Version     <- pkg_meta_athlytics$Version     %||% "0.0.0"
pkg_meta_athlytics$URL         <- pkg_meta_athlytics$URL         %||% "" # Default to empty string if not found
# Ensure 'Packaged' is present for year extraction.
# If it came from packageDescription, it should be there.
# If from DESCRIPTION read or fallback, it might be missing.
pkg_meta_athlytics$Packaged    <- pkg_meta_athlytics$Packaged    %||% default_packaged_date_for_year

# Safely extract year from Packaged date
year_athlytics <- substr(pkg_meta_athlytics$Packaged, 1, 4)
# Validate extracted year, fallback to current year if invalid
if (is.na(year_athlytics) || !grepl("^\\d{4}$", year_athlytics)) {
    year_athlytics <- current_year_text
}

# Safely parse Authors@R string to person objects
bib_author_parsed <- tryCatch({
    eval(parse(text = pkg_meta_athlytics$`Authors@R`))
}, error = function(e) {
    # message(paste("Error parsing Authors@R in CITATION:", e$message)) # Optional debug
    person(given = "Unknown", family = "Author") # Fallback author
})

# Safely get the first URL from a potentially comma-separated list
main_url_processed <- ""
url_field <- pkg_meta_athlytics$URL
if (length(url_field) == 1 && !is.na(url_field) && nzchar(url_field)) {
    main_url_processed <- strsplit(url_field, ",\\s*")[[1]][1]
}

# Software/Manual entry for the package
utils::bibentry(
  bibtype = "Manual",
  title   = paste(pkg_meta_athlytics$Package, ": ", pkg_meta_athlytics$Title, sep = ""),
  author  = bib_author_parsed,
  year    = year_athlytics,
  note    = paste("R package version", pkg_meta_athlytics$Version),
  url     = main_url_processed
)

# Entry for the associated preprint
utils::bibentry(
  bibtype = "Article", # Using "Article" as bibtype for preprint
  title = "Athlytics: A Computational Framework for Longitudinal Analysis of Exercise Physiology Metrics from Wearable Sensor Data",
  author = utils::person(given = "Zhiang", family = "HE"),
  year = "2025",
  journal = "bioRxiv",
  doi = "10.1101/2025.05.01.651597",
  url = "https://www.biorxiv.org/content/10.1101/2025.05.01.651597v2", # URL to the specific version of the preprint
  note = "Preprint"
)