package com.strmr.ps.data.repository;

import android.util.Log;
import androidx.media3.exoplayer.upstream.CmcdData;
import com.strmr.ps.data.local.entity.TraktAccount;
import com.strmr.ps.data.model.ContentItem;
import com.strmr.ps.data.model.trakt.TraktScrobbleRequest;
import com.strmr.ps.data.remote.api.TraktApiService;
import defpackage.ak1;
import defpackage.ck1;
import defpackage.e6a;
import defpackage.gr3;
import defpackage.kq;
import defpackage.n89;
import defpackage.q38;
import defpackage.s38;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import kotlin.Metadata;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.jvm.internal.Boxing;
import kotlin.coroutines.jvm.internal.DebugMetadata;
import kotlin.coroutines.jvm.internal.SuspendLambda;
import okhttp3.Headers;
import retrofit2.HttpException;
import retrofit2.Response;

/* JADX INFO: loaded from: classes3.dex */
@Metadata(d1 = {"\u0000\u0010\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\u0010\u0003\u001a\b\u0012\u0004\u0012\u00020\u00020\u0001*\u00020\u0000H\n¢\u0006\u0004\b\u0003\u0010\u0004"}, d2 = {"Lak1;", "Lq38;", "Le6a;", "<anonymous>", "(Lak1;)Lq38;"}, k = 3, mv = {2, 0, 0})
@DebugMetadata(c = "com.strmr.ps.data.repository.TraktScrobbleRepository$stopWatching$2", f = "TraktScrobbleRepository.kt", i = {0, 1, 1, 2, 3, 3}, l = {297, 342, 349, 359}, m = "invokeSuspend", n = {"stoppingSessionKey", "stoppingSessionKey", "progress", "stoppingSessionKey", "stoppingSessionKey", "progress"}, s = {"L$0", "L$0", "D$0", "L$0", "L$0", "D$0"})
public final class TraktScrobbleRepository$stopWatching$2 extends SuspendLambda implements gr3<ak1, Continuation<? super q38<? extends e6a>>, Object> {
    final /* synthetic */ ContentItem $contentItem;
    final /* synthetic */ long $currentPositionMs;
    final /* synthetic */ long $durationMs;
    final /* synthetic */ Integer $episode;
    final /* synthetic */ Integer $season;
    double D$0;
    Object L$0;
    int label;
    final /* synthetic */ TraktScrobbleRepository this$0;

    /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
    public TraktScrobbleRepository$stopWatching$2(TraktScrobbleRepository traktScrobbleRepository, ContentItem contentItem, Integer num, Integer num2, long j, long j2, Continuation<? super TraktScrobbleRepository$stopWatching$2> continuation) {
        super(2, continuation);
        this.this$0 = traktScrobbleRepository;
        this.$contentItem = contentItem;
        this.$season = num;
        this.$episode = num2;
        this.$currentPositionMs = j;
        this.$durationMs = j2;
    }

    @Override // kotlin.coroutines.jvm.internal.BaseContinuationImpl
    public final Continuation<e6a> create(Object obj, Continuation<?> continuation) {
        return new TraktScrobbleRepository$stopWatching$2(this.this$0, this.$contentItem, this.$season, this.$episode, this.$currentPositionMs, this.$durationMs, continuation);
    }

    @Override // defpackage.gr3
    public final Object invoke(ak1 ak1Var, Continuation<? super q38<e6a>> continuation) {
        return ((TraktScrobbleRepository$stopWatching$2) create(ak1Var, continuation)).invokeSuspend(e6a.a);
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Removed duplicated region for block: B:104:0x02b5  */
    /* JADX WARN: Removed duplicated region for block: B:126:0x034e  */
    /* JADX WARN: Removed duplicated region for block: B:73:0x01c0  */
    /* JADX WARN: Removed duplicated region for block: B:77:0x01f0  */
    /* JADX WARN: Removed duplicated region for block: B:99:0x0289  */
    @Override // kotlin.coroutines.jvm.internal.BaseContinuationImpl
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public final Object invokeSuspend(Object obj) {
        Integer num;
        Headers headers;
        String str;
        Long lBf;
        String str2;
        Object obj2;
        Object objRefreshTokenIfNeeded;
        String str3;
        String str4;
        double d;
        String str5;
        Integer num2;
        String str6;
        double d2;
        Integer num3;
        Integer num4;
        String str7;
        TraktScrobbleRepository traktScrobbleRepository;
        ContentItem contentItem;
        Integer num5;
        Integer num6;
        Integer num7;
        Integer num8;
        String str8;
        Integer num9;
        Object obj3 = ck1.a;
        int i = this.label;
        String str9 = "";
        e6a e6aVar = e6a.a;
        try {
            try {
            } catch (Exception e) {
                e = e;
            }
            if (i == 0) {
                s38.b(obj);
                String str10 = this.this$0.currentSessionKey;
                if (this.$contentItem.getItemType() == ContentItem.ItemType.TV_SHOW && !this.this$0.isValidEpisodeInfo(this.$season, this.$episode)) {
                    Log.w("TraktScrobble", "Skipping stop scrobble for TV show - invalid episode info");
                    this.this$0.resetStateIfStillOwner(str10);
                    return new q38(e6aVar);
                }
                TraktAccountRepository traktAccountRepository = this.this$0.accountRepository;
                this.L$0 = str10;
                this.label = 1;
                objRefreshTokenIfNeeded = traktAccountRepository.refreshTokenIfNeeded(this);
                str3 = str10;
                if (objRefreshTokenIfNeeded != obj3) {
                }
                return obj3;
            }
            if (i != 1) {
                if (i != 2) {
                    if (i == 3) {
                        String str11 = (String) this.L$0;
                        s38.b(obj);
                        obj2 = str11;
                        str2 = obj2;
                        this.this$0.resetStateIfStillOwner(str2);
                        return new q38(e6aVar);
                    }
                    if (i != 4) {
                        throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
                    }
                    d = this.D$0;
                    String str12 = (String) this.L$0;
                    s38.b(obj);
                    str4 = str12;
                    ExecutorService executorService = kq.a;
                    int i2 = (int) d;
                    String title = this.$contentItem.getTitle();
                    num8 = this.$season;
                    if (num8 != null || (num9 = this.$episode) == null) {
                        str8 = "";
                    } else {
                        str8 = " S" + num8 + "E" + num9;
                    }
                    kq.h("TraktScrobble", "Paused watching at " + i2 + "% on exit: " + title + str8);
                    this.this$0.activitiesCache.invalidate();
                    obj2 = str4;
                    str2 = obj2;
                    this.this$0.resetStateIfStillOwner(str2);
                    return new q38(e6aVar);
                }
                d2 = this.D$0;
                str6 = (String) this.L$0;
                try {
                    s38.b(obj);
                    str6 = str6;
                    ExecutorService executorService2 = kq.a;
                    int i3 = (int) d2;
                    String title2 = this.$contentItem.getTitle();
                    num4 = this.$season;
                    if (num4 != null || (num7 = this.$episode) == null) {
                        str7 = "";
                    } else {
                        str7 = " S" + num4 + "E" + num7;
                    }
                    kq.h("TraktScrobble", "Stopped watching at " + i3 + "% (marked watched): " + title2 + str7);
                    traktScrobbleRepository = this.this$0;
                    contentItem = this.$contentItem;
                    num5 = this.$season;
                    num6 = this.$episode;
                    this.L$0 = str6;
                    this.label = 3;
                } catch (Exception e2) {
                    e = e2;
                    obj3 = str6;
                    if (e instanceof HttpException) {
                    }
                }
                if (traktScrobbleRepository.handleWatchedSideEffects(contentItem, num5, num6, this) != obj3) {
                    obj2 = str6;
                    str2 = obj2;
                    this.this$0.resetStateIfStillOwner(str2);
                    return new q38(e6aVar);
                }
                return obj3;
            }
            String str13 = (String) this.L$0;
            s38.b(obj);
            objRefreshTokenIfNeeded = obj;
            str3 = str13;
            TraktAccount traktAccount = (TraktAccount) objRefreshTokenIfNeeded;
            if (traktAccount == null) {
                this.this$0.resetStateIfStillOwner(str3);
                return new q38(e6aVar);
            }
            if (str3 == null) {
                return new q38(e6aVar);
            }
            if (this.this$0.hasScrobbled) {
                this.$contentItem.getTitle();
                if (this.$season != null) {
                    Integer num10 = this.$episode;
                }
                this.this$0.resetStateIfStillOwner(str3);
                return new q38(e6aVar);
            }
            double dCalculateProgress = this.this$0.calculateProgress(this.$currentPositionMs, this.$durationMs);
            double d3 = dCalculateProgress < 1.0d ? 1.0d : dCalculateProgress;
            if (System.currentTimeMillis() < this.this$0.rateLimitBackoffUntilMs) {
                ExecutorService executorService3 = kq.a;
                long jCurrentTimeMillis = (this.this$0.rateLimitBackoffUntilMs - System.currentTimeMillis()) / ((long) 1000);
                String title3 = this.$contentItem.getTitle();
                Integer num11 = this.$season;
                if (num11 != null && (num3 = this.$episode) != null) {
                    str9 = " S" + num11 + "E" + num3;
                }
                kq.h("TraktScrobble", "Skipping exit scrobble — rate limit backoff active (" + jCurrentTimeMillis + "s remaining): " + title3 + str9);
                this.this$0.resetStateIfStillOwner(str3);
                return new q38(e6aVar);
            }
            TraktScrobbleRequest traktScrobbleRequestBuildScrobbleRequest = this.this$0.buildScrobbleRequest(this.$contentItem, this.$season, this.$episode, d3);
            double d4 = d3;
            try {
            } catch (Exception e3) {
                e = e3;
                obj3 = str3;
                if (e instanceof HttpException) {
                    Boxing.boxInt(Log.e("TraktScrobble", "Failed to send exit scrobble", e));
                    obj2 = obj3;
                } else {
                    HttpException httpException = (HttpException) e;
                    int iCode = httpException.code();
                    if (iCode == 422) {
                        ExecutorService executorService4 = kq.a;
                        String title4 = this.$contentItem.getTitle();
                        Integer num12 = this.$season;
                        if (num12 != null && (num = this.$episode) != null) {
                            str9 = " S" + num12 + "E" + num;
                        }
                        kq.h("TraktScrobble", "Exit scrobble returned 422 (session likely expired or already stopped): " + title4 + str9);
                        obj2 = obj3;
                    } else if (iCode != 429) {
                        Boxing.boxInt(Log.e("TraktScrobble", "Failed to send exit scrobble", e));
                        obj2 = obj3;
                    } else {
                        Response<?> response = httpException.response();
                        long jLongValue = (response == null || (headers = response.headers()) == null || (str = headers.get("Retry-After")) == null || (lBf = n89.bf(str)) == null) ? 300L : lBf.longValue();
                        this.this$0.rateLimitBackoffUntilMs = (((long) 1000) * jLongValue) + System.currentTimeMillis();
                        ExecutorService executorService5 = kq.a;
                        kq.h("TraktScrobble", "Exit scrobble rate limited (429), backoff set for " + jLongValue + CmcdData.STREAMING_FORMAT_SS);
                        obj2 = obj3;
                    }
                }
            }
            if (d4 >= 90.0d) {
                TraktApiService traktApiService = this.this$0.traktApiService;
                String str14 = "Bearer " + traktAccount.getAccessToken();
                this.L$0 = str3;
                this.D$0 = d4;
                this.label = 2;
                if (traktApiService.stopScrobble(str14, traktScrobbleRequestBuildScrobbleRequest, this) != obj3) {
                    str6 = str3;
                    d2 = d4;
                    ExecutorService executorService22 = kq.a;
                    int i32 = (int) d2;
                    String title22 = this.$contentItem.getTitle();
                    num4 = this.$season;
                    if (num4 != null) {
                        str7 = "";
                        kq.h("TraktScrobble", "Stopped watching at " + i32 + "% (marked watched): " + title22 + str7);
                        traktScrobbleRepository = this.this$0;
                        contentItem = this.$contentItem;
                        num5 = this.$season;
                        num6 = this.$episode;
                        this.L$0 = str6;
                        this.label = 3;
                        if (traktScrobbleRepository.handleWatchedSideEffects(contentItem, num5, num6, this) != obj3) {
                        }
                    }
                    this.this$0.resetStateIfStillOwner(str2);
                    return new q38(e6aVar);
                }
            } else {
                if (d4 >= 80.0d) {
                    ExecutorService executorService6 = kq.a;
                    int i4 = (int) d4;
                    String title5 = this.$contentItem.getTitle();
                    Integer num13 = this.$season;
                    if (num13 == null || (num2 = this.$episode) == null) {
                        str5 = "";
                    } else {
                        str5 = " S" + num13 + "E" + num2;
                    }
                    kq.h("TraktScrobble", "Exited in 80-89% dead zone (" + i4 + "%), keeping last CW entry: " + title5 + str5);
                    str2 = str3;
                    this.this$0.resetStateIfStillOwner(str2);
                    return new q38(e6aVar);
                }
                TraktApiService traktApiService2 = this.this$0.traktApiService;
                String str15 = "Bearer " + traktAccount.getAccessToken();
                this.L$0 = str3;
                this.D$0 = d4;
                this.label = 4;
                if (traktApiService2.pauseScrobble(str15, traktScrobbleRequestBuildScrobbleRequest, this) != obj3) {
                    str4 = str3;
                    d = d4;
                    ExecutorService executorService7 = kq.a;
                    int i22 = (int) d;
                    String title6 = this.$contentItem.getTitle();
                    num8 = this.$season;
                    if (num8 != null) {
                        str8 = "";
                        kq.h("TraktScrobble", "Paused watching at " + i22 + "% on exit: " + title6 + str8);
                        this.this$0.activitiesCache.invalidate();
                        obj2 = str4;
                        str2 = obj2;
                    }
                    this.this$0.resetStateIfStillOwner(str2);
                    return new q38(e6aVar);
                }
            }
            return obj3;
        } catch (CancellationException e4) {
            throw e4;
        }
    }
}
