package com.github.nullptroma.wallenc.ui.screens.main.screens.storage.twofa

import androidx.core.net.toUri

data class ParsedOtpAuthToken(
    val issuer: String,
    val account: String,
    val secret: String,
    val digits: Int,
    val periodSeconds: Int,
    val algorithm: String,
)

fun parseOtpAuthTotpUri(raw: String): ParsedOtpAuthToken? {
    val uri = runCatching { raw.trim().toUri() }.getOrNull() ?: return null
    if (!uri.scheme.equals("otpauth", ignoreCase = true)) return null
    if (!uri.host.equals("totp", ignoreCase = true)) return null

    val secret = uri.getQueryParameter("secret")?.trim().orEmpty()
    if (secret.isBlank()) return null

    val label = uri.path.orEmpty().trim('/').trim()
    val queryIssuer = uri.getQueryParameter("issuer")?.trim().orEmpty()
    val (issuerFromLabel, accountFromLabel) = splitLabel(label)
    val issuer = queryIssuer.ifBlank { issuerFromLabel }.ifBlank { "TOTP" }
    val account = accountFromLabel.ifBlank { label.ifBlank { "account" } }
    val digits = uri.getQueryParameter("digits")?.toIntOrNull()?.coerceIn(6, 8) ?: 6
    val periodSeconds = uri.getQueryParameter("period")?.toIntOrNull()?.coerceAtLeast(1) ?: 30
    val algorithm = normalizeAlgorithm(uri.getQueryParameter("algorithm") ?: "SHA1")

    return ParsedOtpAuthToken(
        issuer = issuer,
        account = account,
        secret = secret,
        digits = digits,
        periodSeconds = periodSeconds,
        algorithm = algorithm,
    )
}

private fun splitLabel(label: String): Pair<String, String> {
    val idx = label.indexOf(':')
    return if (idx >= 0) {
        label.substring(0, idx).trim() to label.substring(idx + 1).trim()
    } else {
        "" to label.trim()
    }
}

private fun normalizeAlgorithm(input: String): String {
    val normalized = input
        .trim()
        .uppercase()
        .replace("HMAC", "")
        .replace("-", "")
        .replace("_", "")
    return when (normalized) {
        "SHA1", "SHA256", "SHA512" -> normalized
        else -> "SHA1"
    }
}
