package com.miraclegarden.smsmessage.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.miraclegarden.smsmessage.Activity.NotificationActivity;
import com.miraclegarden.smsmessage.App;
import com.miraclegarden.smsmessage.AppConfig;
import com.miraclegarden.smsmessage.MessageInfo;
import com.miraclegarden.smsmessage.network.DebugForwarder;

/**
 * 接收 Xposed 模块转发的消息（Hook 通道）。
 * 在 Receiver 内直接转发到 PC，避免依赖 startService（后台易被系统拦截）。
 */
public class HookMessageReceiver extends BroadcastReceiver {

    private static final String TAG = "HookMessageReceiver";

    public static final String ACTION_HOOK_MESSAGE = "com.miraclegarden.smsmessage.action.HOOK_MESSAGE";
    public static final String EXTRA_PACKAGE_NAME = "packageName";
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_CONTENT = "content";
    public static final String EXTRA_TIMESTAMP = "timestamp";
    public static final String EXTRA_SOURCE = "source";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || !ACTION_HOOK_MESSAGE.equals(intent.getAction())) {
            return;
        }

        String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME);
        String title = intent.getStringExtra(EXTRA_TITLE);
        String content = intent.getStringExtra(EXTRA_CONTENT);
        long timestamp = intent.getLongExtra(EXTRA_TIMESTAMP, System.currentTimeMillis());
        String source = intent.getStringExtra(EXTRA_SOURCE);

        if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(content)) {
            Log.w(TAG, "ignore hook: empty package or content");
            return;
        }

        MessageInfo messageInfo = App.getMessageByNotiList(context, packageName);
        if (messageInfo == null) {
            Log.w(TAG, "ignore hook: not in monitor list, pkg=" + packageName);
            NotificationActivity.sendMessage("[Hook] 未配置监听: " + packageName);
            return;
        }

        if (TextUtils.isEmpty(title)) {
            title = messageInfo.getAppName();
        }

        Log.i(TAG, "hook received: pkg=" + packageName + " source=" + source + " title=" + title);

        final String finalTitle = title;
        NotificationActivity.sendMessage("[Hook/" + source + "] " + finalTitle + " " + content);

        Context appContext = context.getApplicationContext();
        PendingResult pendingResult = goAsync();

        Runnable finish = pendingResult::finish;
        Runnable afterForward = () -> {
            if (AppConfig.ENABLE_SERVER_UPLOAD) {
                NotificationService.submitFromHook(appContext, messageInfo, finalTitle, content, timestamp, source);
            }
            finish.run();
        };

        if (AppConfig.ENABLE_DEBUG_FORWARD) {
            DebugForwarder.forward(appContext, messageInfo, finalTitle, content, timestamp, source, afterForward);
        } else {
            afterForward.run();
        }
    }
}
