package xyz.cottongin.radio247.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import java.io.File
import kotlin.math.abs

object ArtworkGenerator {

    private val PALETTE = intArrayOf(
        0xFF1E88E5.toInt(), // Blue
        0xFF43A047.toInt(), // Green
        0xFFE53935.toInt(), // Red
        0xFF8E24AA.toInt(), // Purple
        0xFFFB8C00.toInt(), // Orange
        0xFF00ACC1.toInt(), // Cyan
        0xFF3949AB.toInt(), // Indigo
        0xFF7CB342.toInt(), // Light Green
        0xFFD81B60.toInt(), // Pink
        0xFF5E35B1.toInt(), // Deep Purple
        0xFF039BE5.toInt(), // Light Blue
        0xFFC0CA33.toInt(), // Lime
    )

    fun extractInitials(name: String): String {
        val words = name.trim().split("\\s+".toRegex()).filter { it.isNotEmpty() }
        return when {
            words.size >= 2 -> "${words[0].first().uppercaseChar()}${words[1].first().uppercaseChar()}"
            words.size == 1 && words[0].length >= 2 -> words[0].take(2).uppercase()
            words.size == 1 -> words[0].first().uppercaseChar().toString()
            else -> "?"
        }
    }

    fun pickColor(name: String): Int {
        return PALETTE[abs(name.hashCode()) % PALETTE.size]
    }

    fun generateBitmap(name: String, sizePx: Int = 256): Bitmap {
        val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)

        val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = pickColor(name)
            style = Paint.Style.FILL
        }
        val cx = sizePx / 2f
        val cy = sizePx / 2f
        canvas.drawCircle(cx, cy, cx, bgPaint)

        val initials = extractInitials(name)
        val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.WHITE
            textSize = sizePx * 0.38f
            typeface = Typeface.DEFAULT_BOLD
            textAlign = Paint.Align.CENTER
        }
        val textY = cy - (textPaint.descent() + textPaint.ascent()) / 2f
        canvas.drawText(initials, cx, textY, textPaint)

        return bitmap
    }

    fun generateAndSave(context: Context, stationId: Long, stationName: String): String {
        val dir = File(context.filesDir, "station_art")
        dir.mkdirs()
        val file = File(dir, "$stationId.png")
        val bitmap = generateBitmap(stationName)
        file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
        bitmap.recycle()
        return file.toURI().toString()
    }
}
