package com.hs.sosnow;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

@SuppressWarnings("deprecation")
public class SmartEvidenceService extends Service {

    public static boolean isServiceRunning = false;

    private MediaRecorder audioRecorder;
    private File currentAudioFile;
    private int batteryLevel = 100;
    private String incidentToken = "";
    private final Handler handler = new Handler(Looper.getMainLooper());

    private SurfaceTexture dummySurfaceBack;
    private SurfaceTexture dummySurfaceFront;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            incidentToken = intent.getStringExtra("INCIDENT_TOKEN");
            if (incidentToken == null || incidentToken.isEmpty()) {
                incidentToken = "INC_" + System.currentTimeMillis();
            }
        }

        isServiceRunning = true;
        startQuietNotification();
        checkBattery();

        // 1. Start Audio Loop
        startAudioCaptureLoop();

        // 2. Start Dual Camera Recording & Snapshot Pipeline
        startDualSyncPipeline();

        return START_STICKY;
    }

    private void checkBattery() {
        try {
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent bStatus = registerReceiver(null, ifilter);
            if (bStatus != null) {
                int level = bStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = bStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                batteryLevel = (int) ((level / (float) scale) * 100);
            }
        } catch (Exception e) {
            batteryLevel = 100;
        }
    }

    private void startQuietNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel("SAFE_GUARD", "Safety Guard", NotificationManager.IMPORTANCE_LOW);
            NotificationManager mgr = getSystemService(NotificationManager.class);
            if (mgr != null) mgr.createNotificationChannel(chan);
        }
        Notification notification = new NotificationCompat.Builder(this, "SAFE_GUARD")
                .setContentTitle("Emergency Guard Active")
                .setContentText("Dual-camera & microphone logging active")
                .setSmallIcon(R.drawable.ic_app_shield_logo)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .build();
        startForeground(3003, notification);
    }

    // ================= CONTINUOUS AUDIO =================
    private void startAudioCaptureLoop() {
        if (!isServiceRunning) return;
        try {
            audioRecorder = new MediaRecorder();
            audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            File outDir = getExternalFilesDir(null);
            currentAudioFile = new File(outDir, "AUD_" + System.currentTimeMillis() + ".m4a");
            audioRecorder.setOutputFile(currentAudioFile.getAbsolutePath());
            audioRecorder.prepare();
            audioRecorder.start();

            handler.postDelayed(() -> {
                stopAndUploadAudio();
                if (isServiceRunning) {
                    startAudioCaptureLoop();
                }
            }, 25000);
        } catch (Exception e) {
            handler.postDelayed(this::startAudioCaptureLoop, 4000);
        }
    }

    private void stopAndUploadAudio() {
        try {
            if (audioRecorder != null) {
                audioRecorder.stop();
                audioRecorder.release();
                audioRecorder = null;
            }
            if (currentAudioFile != null && currentAudioFile.exists()) {
                uploadEvidenceFile(currentAudioFile, "AUDIO");
            }
        } catch (Exception ignored) {}
    }

    // ================= DUAL SYNC CAMERA PIPELINE =================
    private void startDualSyncPipeline() {
        if (!isServiceRunning) return;
        checkBattery();

        long timestamp = System.currentTimeMillis();

        // Step 1: Capture Back Camera frame
        captureCameraSnapshot(Camera.CameraInfo.CAMERA_FACING_BACK, "BACK_" + timestamp, () -> {
            // Step 2: Turant Switch karke Front Camera frame grab (Parallel Sync)
            handler.postDelayed(() -> {
                captureCameraSnapshot(Camera.CameraInfo.CAMERA_FACING_FRONT, "FRONT_" + timestamp, () -> {
                    // Battery conservation timing
                    long nextDelay = (batteryLevel < 25) ? 20000 : 7000;
                    if (isServiceRunning) {
                        handler.postDelayed(this::startDualSyncPipeline, nextDelay);
                    }
                });
            }, 800);
        });
    }

    private void captureCameraSnapshot(int facing, String filePrefix, Runnable onComplete) {
        new Thread(() -> {
            Camera camera = null;
            try {
                int cameraId = -1;
                int count = Camera.getNumberOfCameras();
                for (int i = 0; i < count; i++) {
                    Camera.CameraInfo info = new Camera.CameraInfo();
                    Camera.getCameraInfo(i, info);
                    if (info.facing == facing) {
                        cameraId = i;
                        break;
                    }
                }

                if (cameraId == -1) {
                    if (onComplete != null) handler.post(onComplete);
                    return;
                }

                camera = Camera.open(cameraId);
                SurfaceTexture texture = new SurfaceTexture(facing == Camera.CameraInfo.CAMERA_FACING_BACK ? 10 : 20);
                camera.setPreviewTexture(texture);
                camera.startPreview();

                Thread.sleep(350);

                final Camera activeCam = camera;
                camera.takePicture(null, null, (data, cam) -> {
                    try {
                        File outDir = getExternalFilesDir(null);
                        File photoFile = new File(outDir, filePrefix + ".jpg");
                        FileOutputStream fos = new FileOutputStream(photoFile);
                        fos.write(data);
                        fos.close();

                        uploadEvidenceFile(photoFile, "IMAGE");
                    } catch (Exception ignored) {} finally {
                        try {
                            activeCam.stopPreview();
                            activeCam.release();
                        } catch (Exception ignored) {}
                        if (onComplete != null) handler.post(onComplete);
                    }
                });

            } catch (Exception e) {
                if (camera != null) {
                    try {
                        camera.stopPreview();
                        camera.release();
                    } catch (Exception ignored) {}
                }
                if (onComplete != null) handler.post(onComplete);
            }
        }).start();
    }

    private void uploadEvidenceFile(File file, String type) {
        new Thread(() -> {
            SharedPreferences prefs = getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);
            String token = prefs.getString("AUTH_TOKEN", "");
            String boundary = "===" + System.currentTimeMillis() + "===";

            try {
                URL url = new URL(AppConfig.SERVER_BASE_URL + "?action=upload_evidence");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setConnectTimeout(15000);
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                conn.setRequestProperty("Authorization", token);

                OutputStream os = conn.getOutputStream();
                PrintWriter w = new PrintWriter(os, true);

                w.append("--").append(boundary).append("\r\n");
                w.append("Content-Disposition: form-data; name=\"evidence_type\"\r\n\r\n").append(type).append("\r\n");

                w.append("--").append(boundary).append("\r\n");
                w.append("Content-Disposition: form-data; name=\"battery_level\"\r\n\r\n").append(String.valueOf(batteryLevel)).append("\r\n");

                w.append("--").append(boundary).append("\r\n");
                w.append("Content-Disposition: form-data; name=\"incident_token\"\r\n\r\n").append(incidentToken).append("\r\n");

                w.append("--").append(boundary).append("\r\n");
                w.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(file.getName()).append("\"\r\n");
                w.append("Content-Type: application/octet-stream\r\n\r\n");
                w.flush();

                FileInputStream fis = new FileInputStream(file);
                byte[] buf = new byte[4096];
                int len;
                while ((len = fis.read(buf)) != -1) os.write(buf, 0, len);
                os.flush();
                fis.close();

                w.append("\r\n--").append(boundary).append("--\r\n").flush();
                conn.getResponseCode();
            } catch (Exception ignored) {}
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isServiceRunning = false;
        try {
            if (audioRecorder != null) {
                audioRecorder.stop();
                audioRecorder.release();
            }
        } catch (Exception ignored) {}
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) { return null; }
}