package com.aletheia.app.ui.reader

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong

class ReaderStateCoordinator {
    private val nextRevision = AtomicLong(0L)
    private val positions = ConcurrentHashMap<Long, ReaderSessionPosition>()
    private val persistedSignatures = ConcurrentHashMap<Long, String>()

    fun publish(
        bookId: Long,
        progress: Double,
        locator: String?,
        chapter: String?,
        currentPage: Int,
        totalPages: Int,
        chapterCurrentPage: Int,
        chapterTotalPages: Int
    ): ReaderSessionPosition {
        val snapshot = ReaderSessionPosition(
            revision = nextRevision.incrementAndGet(),
            bookId = bookId,
            progress = if (progress.isFinite()) progress.coerceIn(0.0, 1.0) else 0.0,
            locator = locator,
            chapter = chapter,
            currentPage = currentPage.coerceAtLeast(1),
            totalPages = totalPages.coerceAtLeast(1),
            chapterCurrentPage = chapterCurrentPage.coerceAtLeast(1),
            chapterTotalPages = chapterTotalPages.coerceAtLeast(1)
        )
        positions.compute(bookId) { _, current ->
            if (current == null || snapshot.revision > current.revision) snapshot else current
        }
        return snapshot
    }

    fun latest(bookId: Long): ReaderSessionPosition? = positions[bookId]

    fun lastPersistedSignature(bookId: Long): String? = persistedSignatures[bookId]

    fun markPersisted(bookId: Long, signature: String) {
        persistedSignatures[bookId] = signature
    }

    fun clear(bookId: Long) {
        positions.remove(bookId)
        persistedSignatures.remove(bookId)
    }
}

data class ReaderSessionPosition(
    val revision: Long,
    val bookId: Long,
    val progress: Double,
    val locator: String?,
    val chapter: String?,
    val currentPage: Int,
    val totalPages: Int,
    val chapterCurrentPage: Int,
    val chapterTotalPages: Int
)
