package aza.instant

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Picture
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
import com.ashampoo.kim.Kim
import com.ashampoo.kim.format.tiff.constant.TiffTag
import com.ashampoo.kim.model.MetadataUpdate
import com.ashampoo.kim.model.TiffOrientation
import com.caverock.androidsvg.SVG
import com.caverock.androidsvg.SVGExternalFileResolver
import qrcode.QRCode
import qrcode.raw.ErrorCorrectionLevel
import java.io.ByteArrayOutputStream
import java.util.Base64
import kotlin.io.path.Path
import kotlin.io.path.readBytes

fun createQRCode(url: String) =
    QRCode.ofSquares().withSize(5).withMargin(0).withErrorCorrectionLevel(ErrorCorrectionLevel.LOW)
        .withInnerSpacing(0).build(url).render()

suspend fun genSvg(template: String, imagePath: String): Pair<String, ExifResult> {
    var svg = template

    // Read target image's EXIF data
    var imageData = Path(imagePath).readBytes()
    val exif = parseExif(imageData) ?: error("No EXIF data found")
    println(exif)
    val qr = createQRCode("https://p.aza.moe/${exif.urlName}")
    val stream = ByteArrayOutputStream().also { qr.writeImage(it) }

    // Check EXIF rotation: If it's vertical, rotate the image before embedding
    println("Width: ${exif.w}, Height: ${exif.h}, Orientation: ${exif.d.orientation}")
    if (exif.w < exif.h) {
        println("Vertical image, rotating...")
        imageData = Kim.update(imageData, MetadataUpdate.Orientation(exif.d.orientation?.rotateRight() ?: TiffOrientation.ROTATE_RIGHT))
    }

    svg = svg.replace("2025-09-26  14:59", exif.dateTime)
        .replace("Nag<tspan x=\"1309.04px 1369.61px 1408.89px 1468.58px 1508.64px \" y=\"4531.84px 4531.84px 4531.84px 4531.84px 4531.84px \">atoro</tspan>, Saitama, Japan", exif.location)
//        .replace("""Son<tspan x="4080.43px " y="4377.36px ">y</tspan> IL<tspan x="4189.39px " y="4377.36px ">C</tspan>E-6700 + T<tspan x="4553.27px " y="4377.36px ">a</tspan>mr<tspan x="4679.42px " y="4377.36px ">o</tspan>n 18-300 F3.5-6.3""", exif.cameraInfo)
        .replace("245mm  F6.3  1/500s  ISO-100", exif.shutterInfo)
        .replace("a12ym", exif.urlName)
        .replace("""<image id="_Image1" width="6192px" height="4128px" xlink:href="data:image/jpeg;base64,.*?"/>""".toRegex(),
            """<image id="_Image1" width="6192px" height="4128px" preserveAspectRatio="xMidYMid slice" xlink:href="data:image/jpeg;base64,${Base64.getEncoder().encodeToString(imageData)}"/>""")
        .replace("""<image id="_Image3" width="100px" height="100px" xlink:href="data:image/png;base64,.*?"/>""".toRegex(),
            """<image id="_Image3" width="100px" height="100px" xlink:href="data:image/png;base64,${Base64.getEncoder().encodeToString(stream.toByteArray())}"/>""")
    return svg to exif
}

class FontResolver(private val context: Context) : SVGExternalFileResolver() {
    override fun resolveFont(fontFamily: String?, fontWeight: Int, fontStyle: String?): Typeface? {
        if (fontFamily.equals("Quicksand", ignoreCase = true)) {
            val fontRes = when (fontWeight) {
                in 0..400 -> R.raw.quicksand_regular
                in 401..600 -> R.raw.quicksand_medium
                else -> R.raw.quicksand_bold
            }
            return ResourcesCompat.getFont(context, fontRes)
        }
        return super.resolveFont(fontFamily, fontWeight, fontStyle)
    }
}

fun renderSvgAndroid(context: Context, svg: String): Picture? {
    SVG.registerExternalFileResolver(FontResolver(context))
    return SVG.getFromString(svg).renderToPicture(7133 / 2, 4904 / 2)
}

fun renderSvgBytes(context: Context, svg: String, exif: ExifResult) = renderSvgAndroid(context, svg)?.run {
    var img = ByteArrayOutputStream().also {
        Bitmap.createBitmap(this).compress(Bitmap.CompressFormat.JPEG, 90, it)
    }.toByteArray()

    // If vertical, rotate back
    if (exif.w < exif.h) img = Kim.update(img, MetadataUpdate.Orientation(TiffOrientation.ROTATE_LEFT))

    this to img
}
