package ru.fincode.tsudesk.feature.news.data.parser

import org.jsoup.Jsoup
import ru.fincode.tsudesk.feature.news.domain.model.NewsItem
import javax.inject.Inject

/**
 * Чистый парсер HTML архива:
 * - без baseUrl/baseUri
 * - без https://...
 * - парсит grid карточек из view-source
 */
class NewsArchiveHtmlParser @Inject constructor() {

    data class ParsedPage(
        val items: List<NewsItem>,
        val hasNextPage: Boolean
    )

    fun parse(html: String, currentPage: Int): ParsedPage {
        val doc = Jsoup.parse(html)

        val cards = doc.select("main#press-releases-content a.card.card-ghost[href*=/press-releases/]")
        val items = cards.mapNotNull { card ->
            val href = card.attr("href").trim()
            if (href.isBlank() || !href.contains("/press-releases/")) return@mapNotNull null

            val id = href.substringAfterLast('/').takeWhile { it.isDigit() }
            if (id.isBlank()) return@mapNotNull null

            val title = card.selectFirst("h6.card-title")?.text()?.trim().orEmpty()
            if (title.isBlank()) return@mapNotNull null

            val metaText = card.selectFirst("p.card-text")?.text()?.trim().orEmpty()
            val dateText = extractDate(metaText) ?: return@mapNotNull null

            val tags = extractTags(metaText)
            val category = tags.firstOrNull() ?: "Новости"

            val imageUrl = card.selectFirst("img.card-img[src]")
                ?.attr("src")
                ?.trim()
                ?.takeIf { it.isNotBlank() }

            NewsItem(
                id = id,
                title = title,
                dateText = dateText,
                imageUrl = imageUrl,
                category = category,
                url = href
            )
        }.distinctBy { it.id }

        val hasNextPage = doc.select("a[href*=\"page=${currentPage + 1}\"]").isNotEmpty()

        return ParsedPage(items = items, hasNextPage = hasNextPage)
    }

    private fun extractDate(text: String): String? {
        val regex = Regex("""\b\d{2}\.\d{2}\.\d{4}(?:\s+\d{2}:\d{2})?\b""")
        return regex.find(text)?.value
    }

    private fun extractTags(text: String): List<String> {
        val date = extractDate(text) ?: return emptyList()
        val afterDate = text.substringAfter(date).trim()

        return afterDate
            .split("/")
            .map { it.trim() }
            .filter { it.isNotBlank() }
    }
}