package com.ale.rainbow.rn.utils;

import android.content.Context;

import com.ale.rainbow.RBLog;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private final Thread.UncaughtExceptionHandler defaultHandler;
    private final Context context;

    public static final String CRASH_LOG_FILENAME = "crash_log.txt";

    public CrashHandler(Context context) {
        this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.context = context.getApplicationContext();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        android.util.Log.e("CrashHandler", "--- CRASH DETECTED ---");
        try {
            // Delete any old crash log first to ensure we're starting fresh for this crash.
            File logFile = new File(context.getCacheDir(), CRASH_LOG_FILENAME);
            if (logFile.exists()) {
                logFile.delete();
                android.util.Log.e("CrashHandler", "Deleted old crash log file.");
            }

            // Format the crash data
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            String stackTrace = sw.toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
            String timestamp = sdf.format(new Date());

            String crashLog = "--- CRASH DETECTED ON " + timestamp + " ---\n" +
                            "Thread: " + thread.getName() + "\n" +
                            "Exception: " + ex.getMessage() + "\n" +
                            stackTrace +
                            "--- END OF CRASH ---\n\n";
            // Write to a file
            android.util.Log.e("CrashHandler", "Attempting to write crash log to: " + logFile.getAbsolutePath());
            FileWriter writer = new FileWriter(logFile, false); // false = overwrite
            writer.write(crashLog);
            writer.flush();
            writer.close();
            RBLog.info("CrashHandler","Successfully wrote crash log.");
        } catch (Exception e) {
            // If logging fails, we can't do much, but we shouldn't crash the crash handler.
            RBLog.error("CrashHandler"," Failed to write crash log file", e);
            e.printStackTrace();
        } finally {
            RBLog.error("CrashHandler","Passing exception to default handler");
            // Pass the exception to the default handler to let Android process it (e.g., show "App has stopped")
            if (defaultHandler != null) {
                defaultHandler.uncaughtException(thread, ex);
            }
        }
    }

    public static File getCrashLogFile(Context context) {
        return new File(context.getCacheDir(), CRASH_LOG_FILENAME);
    }
}
