import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

@Serializable
data class SpanDto(
    val start: Int,
    val end: Int,
    val bold: Boolean = false,
    val italic: Boolean = false,
    val underline: Boolean = false
)

@Serializable
data class RichTextDto(
    val text: String,
    val spans: List<SpanDto>
)

object AnnotatedStringSerializer {

    fun toJson(value: AnnotatedString): String {
        val spans = value.spanStyles.map {
            SpanDto(
                start = it.start,
                end = it.end,
                bold = it.item.fontWeight != null,
                italic = it.item.fontStyle != null,
                underline = it.item.textDecoration != null
            )
        }

        return Json.encodeToString(
            RichTextDto(
                text = value.text,
                spans = spans
            )
        )
    }

    fun fromJson(json: String): AnnotatedString {
        return try {
            val dto = Json.decodeFromString<RichTextDto>(json)
            val builder = AnnotatedString.Builder(dto.text)

            dto.spans.forEach {
                builder.addStyle(
                    SpanStyle(
                        fontWeight = if (it.bold) androidx.compose.ui.text.font.FontWeight.Bold else null,
                        fontStyle = if (it.italic) androidx.compose.ui.text.font.FontStyle.Italic else null,
                        textDecoration = if (it.underline) androidx.compose.ui.text.style.TextDecoration.Underline else null
                    ),
                    it.start,
                    it.end
                )
            }

            builder.toAnnotatedString()
        } catch (e: Exception) {
            AnnotatedString(json) // fallback plain
        }
    }
}
