package dev.privacyllc.period.feature.export

import android.content.Context
import dev.privacyllc.period.core.datastore.UserPreferences
import dev.privacyllc.period.core.export.ExportedSettings

/**
 * `UserPreferences` to the export's own type, explicitly and totally.
 *
 * This function exists so that adding a preference is a **compile error** until
 * somebody decides whether it belongs in an archive. Mapping field-by-field is
 * the point; a reflective or wholesale copy would carry every future field out
 * of the app by default, which is the opposite of what an export of "only the
 * user's own data" should do.
 *
 * Two fields are excluded on purpose:
 *
 *  - **`adsRemoved`** — a Play entitlement whose own KDoc names Play as the
 *    source of truth. Once an import path exists, a purchase that could be
 *    granted by editing one line of a text file is a purchase that will be.
 *  - **`onboardingCompleted`** — application state, not a fact about the user.
 *    Nobody's archive is improved by knowing they finished a wizard.
 *
 * `checkInCount` is not on `UserPreferences` at all; it is stored separately and
 * is likewise app state.
 */
internal fun UserPreferences.toExportedSettings(): ExportedSettings = ExportedSettings(
    notificationPrivacy = notificationPrivacy.name,
    reminderTime = reminderTime,
    periodApproaching = periodApproachingEnabled,
    periodExpectedToday = periodExpectedTodayEnabled,
    didItStart = didItStartEnabled,
    periodEndCheckIn = periodEndCheckInEnabled,
    fertileWindow = fertileWindowReminderEnabled,
    ovulation = ovulationReminderEnabled,
    // Named for what it is. `biometricLockEnabled` controls whether a
    // fingerprint may stand in for the PIN — it is NOT "the app lock is on",
    // which is derived from whether a PIN exists and lives in :core:security,
    // where the export cannot reach and should not.
    biometricUnlock = biometricLockEnabled,
    theme = theme.name,
)

/**
 * The installed version, read from the package manager rather than a
 * `BuildConfig` constant — so it reports what is actually on the device, which
 * is the number a person reads out when something is wrong.
 *
 * Plain function rather than the `@Composable` it was extracted from, because
 * the exporter needs it off the main thread and two implementations of one fact
 * is how they come to disagree.
 */
internal fun installedVersionName(context: Context): String =
    runCatching {
        context.packageManager.getPackageInfo(context.packageName, 0).versionName
    }.getOrNull() ?: "unknown"
