package com.nothing.camera2magic.hook

import android.util.Log
import java.io.File

private const val TAG = "HalConfigManager"
private const val CONFIG_DIR = "/data/local/camera_magic"
private const val CONFIG_FILE = "$CONFIG_DIR/config.txt"

object HalConfigManager {

    fun isRootAvailable(): Boolean {
        return try {
            val process = Runtime.getRuntime().exec("su -c id")
            val exitCode = process.waitFor()
            exitCode == 0
        } catch (e: Exception) {
            Log.w(TAG, "Root check failed", e)
            false
        }
    }

    fun writeConfig(
        enabled: Boolean,
        sourceMode: String,
        videoPath: String,
        rtspUrl: String
    ): Boolean {
        if (!isRootAvailable()) {
            Log.e(TAG, "Root access not available, cannot write HAL config")
            return false
        }

        val configContent = buildConfigContent(enabled, sourceMode, videoPath, rtspUrl)

        return try {
            val mkdirProcess = Runtime.getRuntime().exec("su -c mkdir -p $CONFIG_DIR")
            mkdirProcess.waitFor()

            val tempFile = File.createTempFile("camera_magic_config", ".txt")
            tempFile.writeText(configContent)

            val copyProcess = Runtime.getRuntime().exec(
                "su -c cp ${tempFile.absolutePath} $CONFIG_FILE"
            )
            val copyExit = copyProcess.waitFor()
            tempFile.delete()

            if (copyExit == 0) {
                val chmodProcess = Runtime.getRuntime().exec("su -c chmod 644 $CONFIG_FILE")
                chmodProcess.waitFor()
                Log.i(TAG, "HAL config written successfully")
                true
            } else {
                Log.e(TAG, "Failed to copy config file, exit code: $copyExit")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "Failed to write HAL config", e)
            false
        }
    }

    fun readConfig(): HalConfig {
        return try {
            val process = Runtime.getRuntime().exec("su -c cat $CONFIG_FILE")
            val exitCode = process.waitFor()
            if (exitCode == 0) {
                val content = process.inputStream.bufferedReader().readText()
                parseConfigContent(content)
            } else {
                HalConfig()
            }
        } catch (e: Exception) {
            Log.w(TAG, "Failed to read HAL config", e)
            HalConfig()
        }
    }

    private fun buildConfigContent(
        enabled: Boolean,
        sourceMode: String,
        videoPath: String,
        rtspUrl: String
    ): String {
        return buildString {
            appendLine("enabled=${if (enabled) "1" else "0"}")
            appendLine("source_mode=$sourceMode")
            appendLine("video_path=$videoPath")
            appendLine("rtsp_url=$rtspUrl")
        }
    }

    private fun parseConfigContent(content: String): HalConfig {
        val config = HalConfig()
        for (line in content.lineSequence()) {
            val trimmed = line.trim()
            if (trimmed.isEmpty() || trimmed.startsWith('#')) continue
            val parts = trimmed.split('=', limit = 2)
            if (parts.size != 2) continue
            when (parts[0]) {
                "enabled" -> config.enabled = parts[1] == "1"
                "source_mode" -> config.sourceMode = parts[1]
                "video_path" -> config.videoPath = parts[1]
                "rtsp_url" -> config.rtspUrl = parts[1]
            }
        }
        return config
    }

    data class HalConfig(
        var enabled: Boolean = false,
        var sourceMode: String = "file",
        var videoPath: String = "/data/local/camera_magic/video.mp4",
        var rtspUrl: String = ""
    )
}
