package com.nate.posedetection

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSSearchPathForDirectoriesInDomains
import platform.Foundation.NSString
import platform.Foundation.NSUserDomainMask
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.writeToFile
import platform.UIKit.UIDevice

@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
private class IosExperimentLogger : ExperimentLogger {
    override val deviceLabel: String =
        "${UIDevice.currentDevice.systemName} ${UIDevice.currentDevice.model} ${UIDevice.currentDevice.systemVersion}"

    override fun write(filename: String, json: String): String? {
        val docs = (NSSearchPathForDirectoriesInDomains(
            NSDocumentDirectory, NSUserDomainMask, true
        ).firstOrNull() as? String) ?: return null
        val dir = "$docs/experiment_logs"
        NSFileManager.defaultManager.createDirectoryAtPath(
            dir, true, null, null
        )
        val path = "$dir/$filename"
        val ok = (json as NSString).writeToFile(
            path = path,
            atomically = true,
            encoding = NSUTF8StringEncoding,
            error = null
        )
        return if (ok) path else null
    }
}

@Composable
actual fun rememberExperimentLogger(): ExperimentLogger = remember { IosExperimentLogger() }
