package com.jishisongfu.duobibi.util

import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import com.jishisongfu.duobibi.data.db.Cluster
import com.jishisongfu.duobibi.data.db.PriceRecord
import java.io.File
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object CsvExporter {

    /**
     * 导出全部价格记录为 CSV,写入 Downloads。
     * 返回写入的文件名。失败抛异常。
     */
    fun export(
        ctx: Context,
        records: List<PriceRecord>,
        clusters: List<Cluster>,
    ): String {
        val ts = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
        val filename = "duobibi_export_$ts.csv"
        val clusterById = clusters.associateBy { it.id }
        val csv = buildCsv(records, clusterById)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            writeViaMediaStore(ctx, filename, csv)
        } else {
            writeToLegacyDownload(ctx, filename, csv)
        }
        return filename
    }

    private fun buildCsv(
        records: List<PriceRecord>,
        clusterById: Map<Long, Cluster>,
    ): String {
        val sb = StringBuilder()
        // BOM,确保 Excel 中文不乱码
        sb.append('\uFEFF')
        sb.append("id,商品名,价格,来源 App,商品组,商品组ID,记录时间\n")
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        records.sortedByDescending { it.createdAt }.forEach { r ->
            val clusterTitle = clusterById[r.clusterId]?.title.orEmpty()
            sb.append(r.id).append(',')
            sb.append(escape(r.title)).append(',')
            sb.append(formatPrice(r.price)).append(',')
            sb.append(escape(r.sourceApp)).append(',')
            sb.append(escape(clusterTitle)).append(',')
            sb.append(r.clusterId).append(',')
            sb.append(escape(df.format(Date(r.createdAt)))).append('\n')
        }
        return sb.toString()
    }

    private fun escape(s: String): String {
        if (s.contains(',') || s.contains('"') || s.contains('\n')) {
            return "\"" + s.replace("\"", "\"\"") + "\""
        }
        return s
    }

    private fun formatPrice(p: Double): String =
        if (p == p.toLong().toDouble()) p.toLong().toString() else "%.2f".format(p)

    private fun writeViaMediaStore(ctx: Context, filename: String, content: String) {
        val resolver = ctx.contentResolver
        val values = ContentValues().apply {
            put(MediaStore.Downloads.DISPLAY_NAME, filename)
            put(MediaStore.Downloads.MIME_TYPE, "text/csv")
            put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
        }
        val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
            ?: error("无法创建文件")
        resolver.openOutputStream(uri).use { out: OutputStream? ->
            out?.write(content.toByteArray(Charsets.UTF_8))
        }
    }

    /**
     * Android 9- 走 app 私有的 Download 目录,无需 WRITE_EXTERNAL_STORAGE 权限。
     * 路径在 /Android/data/<package>/files/Download/,系统卸载 App 时一并清除。
     */
    private fun writeToLegacyDownload(ctx: Context, filename: String, content: String) {
        val dir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
            ?: error("无可用的应用私有外部存储目录")
        if (!dir.exists()) dir.mkdirs()
        File(dir, filename).writeText(content, Charsets.UTF_8)
    }
}
