package com.performancecoachlab.posedetection.custom

import androidx.compose.runtime.Composable
import kotlinx.cinterop.ExperimentalForeignApi
import platform.CoreML.MLModel
import platform.Foundation.NSBundle
import platform.Foundation.NSURL
import platform.Vision.VNCoreMLModel

@Composable
actual fun initialiseObjectModel(modelPath: ModelPath): ObjectModel {
    val model = createObjectDetector(modelPath.iosModelPath)
    return ObjectModel(model)
}

@OptIn(ExperimentalForeignApi::class)
fun createObjectDetector(model: String?): VNCoreMLModel? {
    if (model == null) {
        return null
    }
    //println("Model input: $model")
    val path = NSBundle.mainBundle.pathForResource(model, "mlmodelc")
    //println("Model path: $path")
    val url = path?.let { NSURL.fileURLWithPath(it) }
    //println("Model URL: $url")
    val modelCont = url?.let { MLModel.modelWithContentsOfURL(it, null) }
    //println("Model content: $modelCont")
    val modelObj = modelCont?.let { VNCoreMLModel.modelForMLModel(it, null) }
    //println("Model: $modelObj")
    return modelObj
}

actual class ObjectModel {
    private var model: VNCoreMLModel? = null

    constructor(model: VNCoreMLModel?) {
        this.model = model
    }

    fun getModel(): VNCoreMLModel? {
        return model
    }
}

@Composable
internal actual fun platformRememberObjectModel(modelPath: ModelPath): ObjectModel {
    // iOS: create once for this composition; avoids global caching issues
    return initialiseObjectModel(modelPath)
}