from __future__ import annotations

import time
from typing import TYPE_CHECKING

from ..errors import WhatsrbCloudError

if TYPE_CHECKING:
    from ..client import WhatsrbCloud
    from .business_account import BusinessAccount


class ConnectRequest:
    def __init__(self, data: dict, *, client: WhatsrbCloud | None = None):
        self.id = data.get("id")
        self.url = data.get("url")
        self.status = data.get("status")
        self.expires_at = data.get("expires_at")
        self.error = data.get("error")
        self._client = client
        self._raw = data

        if data.get("account"):
            from .business_account import BusinessAccount
            self.account: BusinessAccount | None = BusinessAccount(data["account"], client=client)
        else:
            self.account = None

    @property
    def is_pending(self) -> bool:
        return self.status == "pending"

    @property
    def is_completed(self) -> bool:
        return self.status == "completed"

    @property
    def is_expired(self) -> bool:
        return self.status == "expired"

    @property
    def is_failed(self) -> bool:
        return self.status == "failed"

    def reload(self) -> ConnectRequest:
        refreshed = self._client.connects.retrieve(self.id)
        self.status = refreshed.status
        self.account = refreshed.account
        self.error = refreshed.error
        self.expires_at = refreshed.expires_at
        return self

    def refresh(self) -> ConnectRequest:
        return self.reload()

    def wait_for_account(self, *, timeout: int = 300, interval: int = 2) -> BusinessAccount:
        deadline = time.time() + timeout

        while True:
            self.reload()
            if self.is_completed and self.account:
                return self.account
            if self.is_expired:
                raise WhatsrbCloudError("Connect request expired")
            if self.is_failed:
                raise WhatsrbCloudError(f"Connect request failed: {self.error}")
            if time.time() >= deadline:
                raise WhatsrbCloudError("Timed out waiting for account connection")
            time.sleep(interval)

    def to_dict(self) -> dict:
        return self._raw
