package com.nate.posedetection

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.tooling.preview.Preview
import com.performancecoachlab.posedetection.recording.VideoExtractionContext
import io.github.vinceglb.filekit.FileKit
import io.github.vinceglb.filekit.dialogs.init

class AppActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FileKit.init(this)
        VideoExtractionContext.setUp(applicationContext)
        enableEdgeToEdge()
        val autoSpec = parseAutoSpec(intent)
        setContent {
            CompositionLocalProvider(LocalExperimentAutoSpec provides autoSpec) {
                App()
            }
        }
    }
}

/**
 * Parses the unattended-experiment extras placed on the launch intent by
 * `tools/run_auto_experiment.sh`. Returns null if the intent does not carry
 * the `experiment_auto` flag, in which case the app behaves normally.
 *
 * Required when `experiment_auto` is true:
 *   --es model_name "<display name or filename, case-insensitive>"
 *   --el start_at_wall_ms <System.currentTimeMillis target>
 *   --el duration_ms <buffer duration>
 * Optional:
 *   --ez finish_on_stop <true|false> (default true)
 */
private fun parseAutoSpec(intent: Intent?): ExperimentLaunchSpec? {
    if (intent == null || !intent.getBooleanExtra("experiment_auto", false)) return null
    val modelName = intent.getStringExtra("model_name").orEmpty()
    val startAtWallMs = intent.getLongExtra("start_at_wall_ms", 0L)
    val durationMs = intent.getLongExtra("duration_ms", 0L)
    val finishOnStop = intent.getBooleanExtra("finish_on_stop", true)
    if (modelName.isBlank() || durationMs <= 0L) return null
    return ExperimentLaunchSpec(
        modelName = modelName,
        startAtWallMs = startAtWallMs,
        durationMs = durationMs,
        finishOnStop = finishOnStop,
    )
}

@Preview
@Composable
fun AppPreview() {
    App()
}
