package com.example.studentfaceregistry.data

import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

class StudentRepository(context: Context) {
    private val storageFile = File(context.filesDir, "students.json")
    private val _students = MutableStateFlow(load())
    val students: StateFlow<List<Student>> = _students

    fun add(student: Student) {
        val next = _students.value.toMutableList().apply { add(student) }
            .sortedByDescending { it.createdAt }
        _students.value = next
        save(next)
    }

    fun clear() {
        _students.value = emptyList()
        save(emptyList())
    }

    private fun load(): List<Student> {
        if (!storageFile.exists()) return emptyList()
        val raw = storageFile.readText()
        if (raw.isBlank()) return emptyList()
        val array = JSONArray(raw)
        return buildList {
            for (index in 0 until array.length()) {
                val obj = array.getJSONObject(index)
                add(
                    Student(
                        id = obj.optLong("id", index.toLong()),
                        studentNo = obj.getString("studentNo"),
                        name = obj.getString("name"),
                        photoUri = obj.getString("photoUri"),
                        embedding = decodeEmbedding(obj.getJSONArray("embedding")),
                        createdAt = obj.optLong("createdAt", System.currentTimeMillis())
                    )
                )
            }
        }
    }

    private fun save(students: List<Student>) {
        val array = JSONArray()
        students.forEach { student ->
            array.put(
                JSONObject().apply {
                    put("id", student.id)
                    put("studentNo", student.studentNo)
                    put("name", student.name)
                    put("photoUri", student.photoUri)
                    put("createdAt", student.createdAt)
                    put("embedding", JSONArray(student.embedding.toList()))
                }
            )
        }
        storageFile.writeText(array.toString())
    }

    private fun decodeEmbedding(array: JSONArray): FloatArray {
        return FloatArray(array.length()) { index -> array.getDouble(index).toFloat() }
    }
}
