package com.aletheia.app.data

import java.net.URI

object CatalogUrlResolver {
    fun resolve(baseUrl: String, pathOrUrl: String): String {
        val base = URI(baseUrl.trimEnd('/') + "/")
        return base.resolve(pathOrUrl).toString()
    }

    fun resolveDownloadRedirect(sourceUrl: String, location: String): String {
        val resolved = URI(sourceUrl).resolve(location.trim())
        val normalized = if (
            resolved.scheme.equals("http", ignoreCase = true) &&
            resolved.host.equals(FLIBUSTA_STATIC_HOST, ignoreCase = true) &&
            resolved.port == HTTPS_PORT
        ) {
            URI(
                "https",
                resolved.userInfo,
                resolved.host,
                -1,
                resolved.path,
                resolved.query,
                resolved.fragment
            )
        } else {
            resolved
        }

        require(normalized.scheme.equals("http", ignoreCase = true) || normalized.scheme.equals("https", ignoreCase = true)) {
            "Каталог вернул ссылку с неподдерживаемой схемой."
        }
        return normalized.toString()
    }

    private const val FLIBUSTA_STATIC_HOST = "staticm.flibusta.is"
    private const val HTTPS_PORT = 443
}
