package com.harshmallow.pilottoolkit.data

import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

private const val PREFS_NAME = "fuel_profiles"

data class FuelProfile(val name: String, val buckets: List<FuelBucket>)

private fun getPrefs(context: Context) = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

fun getFuelProfile(context: Context, aircraftId: String): FuelProfile? {
    val prefs = getPrefs(context)
    val raw = prefs.getString("profile_$aircraftId", null) ?: return null
    return try {
        val obj = JSONObject(raw)
        // Migration: old format was bare JSON array
        if (raw.trimStart().startsWith("[")) {
            val arr = JSONArray(raw)
            val buckets = (0 until arr.length()).map { i ->
                val b = arr.getJSONArray(i)
                FuelBucket(b.getDouble(0), b.getDouble(1))
            }
            FuelProfile("Custom", buckets)
        } else {
            val name = obj.optString("name", "Custom")
            val arr = obj.getJSONArray("buckets")
            val buckets = (0 until arr.length()).map { i ->
                val b = arr.getJSONArray(i)
                FuelBucket(b.getDouble(0), b.getDouble(1))
            }
            FuelProfile(name, buckets)
        }
    } catch (e: Exception) {
        // Try as bare array (old format)
        try {
            val arr = JSONArray(raw)
            val buckets = (0 until arr.length()).map { i ->
                val b = arr.getJSONArray(i)
                FuelBucket(b.getDouble(0), b.getDouble(1))
            }
            FuelProfile("Custom", buckets)
        } catch (e2: Exception) { null }
    }
}

fun saveFuelProfile(context: Context, aircraftId: String, name: String, buckets: List<FuelBucket>) {
    val obj = JSONObject()
    obj.put("name", name)
    val arr = JSONArray()
    buckets.forEach { b ->
        val entry = JSONArray()
        entry.put(b.stageLength)
        entry.put(b.fuelBurn)
        arr.put(entry)
    }
    obj.put("buckets", arr)
    getPrefs(context).edit().putString("profile_$aircraftId", obj.toString()).apply()
}

fun clearFuelProfile(context: Context, aircraftId: String) {
    getPrefs(context).edit().remove("profile_$aircraftId").apply()
}

fun getAllFuelProfiles(context: Context): Map<String, FuelProfile> {
    val map = mutableMapOf<String, FuelProfile>()
    aircraftRegistry.forEach { ac ->
        val profile = getFuelProfile(context, ac.id)
        if (profile != null) map[ac.id] = profile
    }
    return map
}

/* ── CSV Parser ── */
fun parseBucketCSV(text: String): Pair<List<FuelBucket>?, String?> {
    val lines = text.trim().lines().filter { it.isNotBlank() }
    if (lines.isEmpty()) return null to "File is empty."

    val firstFields = lines[0].split(",").map { it.trim() }
    val startsWithHeader = firstFields[0].toDoubleOrNull() == null
    val dataLines = if (startsWithHeader) lines.drop(1) else lines
    if (dataLines.isEmpty()) return null to "No data rows found."

    val buckets = mutableListOf<FuelBucket>()
    dataLines.forEachIndexed { i, line ->
        val fields = line.split(",").map { it.trim() }
        if (fields.size < 2) return null to "Row ${i + 1}: expected 2 columns, found ${fields.size}."
        val stage = fields[0].toDoubleOrNull()
        val burn = fields[1].toDoubleOrNull()
        if (stage == null || burn == null) return null to "Row ${i + 1}: non-numeric value."
        if (stage < 0 || burn < 0) return null to "Row ${i + 1}: negative values not allowed."
        buckets.add(FuelBucket(stage, burn))
    }
    buckets.sortBy { it.stageLength }
    return buckets to null
}

/* ── JSON Profile Export ── */
fun exportFuelProfileJSON(context: Context, aircraftId: String, profile: FuelProfile) {
    val obj = JSONObject()
    obj.put("format", "pilot-toolkit-fuel-profile")
    obj.put("version", 1)
    obj.put("aircraft", aircraftId)
    obj.put("aircraftLabel", getAircraftById(aircraftId).label)
    obj.put("name", profile.name)
    obj.put("entries", profile.buckets.size)
    val arr = JSONArray()
    profile.buckets.forEach { b ->
        val entry = JSONArray()
        entry.put(b.stageLength)
        entry.put(b.fuelBurn)
        arr.put(entry)
    }
    obj.put("buckets", arr)

    val safeName = profile.name.replace(Regex("[^A-Za-z0-9_-]"), "_")
    val filename = "FUEL_PROFILE_${safeName}_${aircraftId}.json"
    val dir = File(context.cacheDir, "exports")
    dir.mkdirs()
    val file = File(dir, filename)
    file.writeText(obj.toString(2))

    val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
    val intent = Intent(Intent.ACTION_SEND).apply {
        type = "application/json"
        putExtra(Intent.EXTRA_STREAM, uri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    context.startActivity(Intent.createChooser(intent, "Share fuel profile"))
}

/* ── JSON Profile Import ── */
fun parseFuelProfileJSON(text: String): Triple<String, String, List<FuelBucket>> {
    val obj = JSONObject(text)
    if (obj.optString("format") != "pilot-toolkit-fuel-profile") {
        throw IllegalArgumentException("Not a valid fuel profile file.")
    }
    val arr = obj.getJSONArray("buckets")
    if (arr.length() == 0) throw IllegalArgumentException("No bucket data found.")
    val name = obj.optString("name", "Imported")
    val aircraft = obj.optString("aircraft", "")
    val buckets = (0 until arr.length()).map { i ->
        val b = arr.getJSONArray(i)
        FuelBucket(b.getDouble(0), b.getDouble(1))
    }.sortedBy { it.stageLength }
    return Triple(name, aircraft, buckets)
}
