package com.hikoncont.service

import android.content.Context
import android.util.Log
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException

/**
 * 心跳检测管理器 - 借鉴反编译项目的心跳文件检测机制
 * 主要职责：
 * 1. 更新心跳文件
 * 2. 检查心跳超时
 * 3. 服务存活检测
 */
class HeartbeatManager private constructor(private val context: Context) {

    companion object {
        private const val TAG = "HeartbeatManager"
        private const val HEARTBEAT_FILE = "service_heartbeat.dat"
        private const val HEARTBEAT_TIMEOUT = 300000L // 5分钟超时（避免误判）
        private const val STATUS_FILE = "service_status.dat"
        
        @Volatile
        private var INSTANCE: HeartbeatManager? = null
        
        fun getInstance(context: Context): HeartbeatManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: HeartbeatManager(context.applicationContext).also { INSTANCE = it }
            }
        }
    }

    /**
     * 更新心跳文件
     */
    fun updateHeartbeat() {
        try {
            val timestamp = System.currentTimeMillis().toString()
            context.openFileOutput(HEARTBEAT_FILE, Context.MODE_PRIVATE).use { fos ->
                fos.write(timestamp.toByteArray())
            }
            Log.d(TAG, "💓 心跳文件已更新: $timestamp")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 更新心跳文件失败", e)
        }
    }

    /**
     * 检查心跳是否超时
     */
    fun isHeartbeatExpired(): Boolean {
        return try {
            context.openFileInput(HEARTBEAT_FILE).use { fis ->
                val buffer = ByteArray(128)
                val bytesRead = fis.read(buffer)
                if (bytesRead > 0) {
                    val timestamp = String(buffer, 0, bytesRead).toLongOrNull() ?: 0L
                    val timeDiff = System.currentTimeMillis() - timestamp
                    val isExpired = timeDiff > HEARTBEAT_TIMEOUT
                    Log.d(TAG, "💓 心跳检查: 时间差=${timeDiff}ms, 超时=${isExpired}")
                    isExpired
                } else {
                    Log.w(TAG, "💓 心跳文件为空，认为超时")
                    true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "💓 读取心跳文件失败，认为超时", e)
            true
        }
    }

    /**
     * 设置服务状态
     */
    fun setServiceStatus(isRunning: Boolean) {
        try {
            val status = if (isRunning) 1 else 0
            context.openFileOutput(STATUS_FILE, Context.MODE_PRIVATE).use { fos ->
                fos.write(status)
            }
            Log.d(TAG, "📊 服务状态已设置: $isRunning")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设置服务状态失败", e)
        }
    }

    /**
     * 获取服务状态
     */
    fun getServiceStatus(): Boolean {
        return try {
            context.openFileInput(STATUS_FILE).use { fis ->
                val status = fis.read()
                status == 1
            }
        } catch (e: Exception) {
            Log.w(TAG, "📊 读取服务状态失败，默认为未运行", e)
            false
        }
    }

    /**
     * 检查服务是否需要重启
     */
    fun shouldRestartService(): Boolean {
        val isExpired = isHeartbeatExpired()
        
        // 暂时禁用服务状态检查，避免误判
        // val isNotRunning = !getServiceStatus()
        
        Log.d(TAG, "🔍 服务重启检查: 心跳超时=$isExpired")
        
        // 只检查心跳超时，不检查服务状态
        return isExpired
    }

    /**
     * 清理心跳文件
     */
    fun clearHeartbeat() {
        try {
            context.deleteFile(HEARTBEAT_FILE)
            Log.d(TAG, "🧹 心跳文件已清理")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理心跳文件失败", e)
        }
    }

    /**
     * 清理状态文件
     */
    fun clearStatus() {
        try {
            context.deleteFile(STATUS_FILE)
            Log.d(TAG, "🧹 状态文件已清理")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理状态文件失败", e)
        }
    }

    /**
     * 获取心跳信息
     */
    fun getHeartbeatInfo(): Map<String, Any> {
        return try {
            val isExpired = isHeartbeatExpired()
            val isRunning = getServiceStatus()
            val shouldRestart = shouldRestartService()
            
            mapOf(
                "heartbeat_expired" to isExpired,
                "service_running" to isRunning,
                "should_restart" to shouldRestart,
                "timeout_threshold" to HEARTBEAT_TIMEOUT
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取心跳信息失败", e)
            emptyMap()
        }
    }
}
