package cc.winboll.studio.contacts.services;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.telecom.CallScreeningService;
import android.telephony.TelephonyManager;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.libappbase.LogUtils;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/12/12 19:00
 * @Describe 通话筛选服务（完全匹配 API 30 父类方法原型，严格 Java 7 兼容）
 * 修复：1. 前台服务启动超时异常  2. 移除所有 Build.VERSION_CODES 高版本依赖  3. 强化空指针防护
 */
@RequiresApi(api = 29) // API 29 = Android 10 = Build.VERSION_CODES.Q，直接写数值避免依赖
public class MyCallScreeningService extends CallScreeningService {
    // ====================== 常量定义区（全硬编码，杜绝高版本 API 依赖） ======================
    public static final String TAG = "MyCallScreeningService";
    // 前台服务配置
    private static final int FOREGROUND_NOTIFICATION_ID = 1003;
    private static final String FOREGROUND_CHANNEL_ID = "call_screening_service_channel";
    // API 版本常量（直接写数值，替代 Build.VERSION_CODES）
    private static final int ANDROID_8_API = 26;       // Android 8.0，通知渠道最低版本
    private static final int ANDROID_12_API = 31;      // Android 12，stopForeground 带参数版本
    // stopForeground 参数常量（硬编码 1，替代 STOP_FOREGROUND_REMOVE）
    private static final int STOP_FOREGROUND_REMOVE = 1;
    // 通话方向常量（直接写数值，替代 Call.Details 中的常量，适配 API 30）
    private static final int CALL_DIRECTION_INCOMING = 1;
    private static final int CALL_DIRECTION_OUTGOING = 2;

    // 成员变量
    private Context mContext;

    // ====================== Service 生命周期方法 ======================
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        LogUtils.d(TAG, "onCreate: 通话筛选服务启动");

        // ========== 核心优化：优先启动前台服务，放在 onCreate 最前端，避免超时 ==========
        try {
            Notification foregroundNotification = createForegroundNotification();
            startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification);
            LogUtils.d(TAG, "onCreate: 前台服务启动成功");
        } catch (Exception e) {
            LogUtils.e(TAG, "onCreate: 前台服务启动失败", e);
            stopSelf(); // 启动失败直接停止服务，避免系统抛出异常
            return;
        }
    }

    /**
     * 100% 匹配 API 30 CallScreeningService 抽象方法原型
     * 完全移除高版本依赖，使用硬编码常量
     */
    @Override
    @RequiresApi(api = 29) // 与类注解一致，明确最低 API 要求
    public void onScreenCall(@NonNull android.telecom.Call.Details details) {
        // 1. 获取通话号码：多层空指针防护，Java 7 规范写法
        String phoneNumber = "未知号码";
        Uri handle = details.getHandle();
        if (handle != null) {
            String schemePart = handle.getSchemeSpecificPart();
            if (schemePart != null && !schemePart.trim().isEmpty()) {
                phoneNumber = schemePart.trim();
            }
        }

        // 2. 判断通话方向：用硬编码常量替代 API 高版本字段
        String callTypeStr;
        int callType;
        int direction = details.getCallDirection();
        if (direction == CALL_DIRECTION_INCOMING) {
            callTypeStr = "来电";
            callType = TelephonyManager.CALL_STATE_RINGING;
        } else if (direction == CALL_DIRECTION_OUTGOING) {
            callTypeStr = "外拨";
            callType = TelephonyManager.CALL_STATE_OFFHOOK;
        } else {
            callTypeStr = "未知类型";
            callType = TelephonyManager.CALL_STATE_IDLE;
        }

        // Java 7 字符串拼接，避免 String.format 兼容性问题
        LogUtils.d(TAG, "检测到" + callTypeStr + "：" + phoneNumber);

        // 3. 自定义拦截逻辑：示例拦截 10086
        boolean shouldBlock = "10086".equals(phoneNumber);

        // 4. 构建筛选响应：Java 7 分步调用，不使用链式写法
        CallResponse.Builder responseBuilder = new CallResponse.Builder();
        responseBuilder.setDisallowCall(shouldBlock);
        responseBuilder.setRejectCall(shouldBlock);
        responseBuilder.setSkipCallLog(!shouldBlock);
        responseBuilder.setSkipNotification(!shouldBlock);
        CallResponse response = responseBuilder.build();

        // 5. 提交筛选结果（API 30 父类方法，直接调用）
        respondToCall(details, response);

        // 6. 处理业务逻辑
        if (!shouldBlock) {
            handleNormalCall(phoneNumber, callType);
        } else {
            LogUtils.d(TAG, "已拦截通话：" + phoneNumber);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy: 通话筛选服务销毁");
        // 适配 Android 12+ stopForeground 参数，硬编码常量避免依赖
        if (Build.VERSION.SDK_INT >= ANDROID_12_API) {
            stopForeground(STOP_FOREGROUND_REMOVE);
        }
    }

    // ====================== 业务逻辑方法 ======================
    /**
     * 处理正常通话的扩展逻辑，Java 7 规范写法，添加空指针防护
     */
    private void handleNormalCall(String phoneNumber, int callType) {
        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
            LogUtils.w(TAG, "handleNormalCall: 号码为空，跳过处理");
            return;
        }
        LogUtils.d(TAG, "处理正常通话：" + phoneNumber + " | 状态：" + getCallStateStr(callType));
        // 可在此添加通话记录、广播通知等逻辑
    }

    /**
     * 辅助方法：将通话状态转为字符串，避免重复代码
     */
    private String getCallStateStr(int callType) {
        switch (callType) {
            case TelephonyManager.CALL_STATE_RINGING:
                return "响铃中";
            case TelephonyManager.CALL_STATE_OFFHOOK:
                return "通话中";
            case TelephonyManager.CALL_STATE_IDLE:
                return "空闲";
            default:
                return "未知";
        }
    }

    // ====================== 前台服务通知构建方法 ======================
    /**
     * 创建前台服务通知：严格 Java 7 分步构建，强化异常防护
     * @return 可用的 Notification 实例
     */
    private Notification createForegroundNotification() {
        // 1. 创建 Android 8.0+ 通知渠道，添加空指针防护
        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            NotificationChannel channel = new NotificationChannel(
				FOREGROUND_CHANNEL_ID,
				"来电筛查服务",
				NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("后台处理来电筛查，防止服务被系统回收");
            // 关闭通知音效和震动，避免打扰用户
            channel.setSound(null, null);
            channel.enableVibration(false);

            NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) {
                manager.createNotificationChannel(channel);
                LogUtils.d(TAG, "createForegroundNotification: 通知渠道创建成功");
            } else {
                LogUtils.e(TAG, "createForegroundNotification: NotificationManager 获取失败");
            }
        }

        // 2. 构建 Notification：Java 7 分步设置，不使用链式调用
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            builder = new Notification.Builder(mContext, FOREGROUND_CHANNEL_ID);
        } else {
            builder = new Notification.Builder(mContext);
        }

        // 关键：确保小图标资源存在，替换为项目实际图标
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("来电筛查服务运行中");
        builder.setContentText("正在监控来电状态");
        builder.setPriority(Notification.PRIORITY_LOW);
        builder.setOngoing(true); // 前台服务通知不可手动取消

        return builder.build();
    }
}

