package org.dueattendant149.bookshelf.domain.util

import android.net.Uri

private val URL_SCHEME_REGEX = Regex("^[hH][tT][tT][pP][sS]?://")

/**
 * Returns true if the string is non-blank, has an http/https scheme,
 * and can be parsed by [Uri.parse] into a host-bearing URI.
 */
fun String.isValidUri(): Boolean {
    val trimmed = trim()
    if (trimmed.isBlank()) return false
    if (!trimmed.hasUriScheme()) return false

    val uri = runCatching { Uri.parse(trimmed) }.getOrNull() ?: return false
    return !uri.host.isNullOrBlank()
}

/**
 * Returns true if the string starts with http:// or https:// (case-insensitive).
 */
fun String.hasUriScheme(): Boolean = matches(URL_SCHEME_REGEX)

/**
 * Adds https:// if the string has no http/https scheme.
 */
fun String.ensureUriScheme(): String {
    val trimmed = trim()
    return if (trimmed.hasUriScheme()) trimmed else "https://$trimmed"
}

/**
 * Adds a trailing slash if missing.
 */
fun String.ensureTrailingSlash(): String {
    val trimmed = trim()
    return if (trimmed.endsWith("/")) trimmed else "$trimmed/"
}

/**
 * Normalizes a URL for Retrofit: trims whitespace, adds a scheme if missing,
 * and ensures a trailing slash.
 */
fun String.normalizeUri(): String = ensureUriScheme().ensureTrailingSlash()

/**
 * Legacy alias for [normalizeUri].
 */
fun String.fixUriScheme(): String = normalizeUri()

/**
 * Derives a likely Audiobookshelf URL from a Bookshelf API URL.
 * Replaces a known bookshelf-api port (8073) with the default ABS port (13378),
 * or appends :13378 when no port is present. Returns null if the input is invalid.
 */
fun String.deriveAbsUrl(): String? {
    if (!isValidUri()) return null
    val normalized = normalizeUri()
    val uri = Uri.parse(normalized)
    val host = uri.host ?: return null
    val port = uri.port
    val scheme = uri.scheme?.lowercase() ?: "https"

    val derivedPort = when (port) {
        8073 -> 13378
        -1 -> 13378
        else -> port
    }
    return "$scheme://$host:$derivedPort/"
}
