import json

import requests
from django.conf import settings

from organization_auth.models import UserAccount
from organization_auth.utils import decrypt_value


USER_ACCOUNT_ID = "4fc420f0-ca36-4c38-a23c-7d069b22ccf0"
ATTEMPTS = 10
GRAPH_VERSION = getattr(settings, "GRAPH_FB_API_VERSION", "v22.0")


def serialize_user_account(user_account):
    return {
        "id": str(user_account.id),
        "user_email": user_account.user.user_email,
        "account_id": str(user_account.account.id),
        "ad_account_id": user_account.account.ad_account_id,
        "ad_account_name": user_account.account.ad_account_name,
        "platform": user_account.account.platform,
        "role": user_account.role,
        "status": user_account.status,
        "last_token_check_time": user_account.last_token_check_time.isoformat()
        if user_account.last_token_check_time
        else None,
        "has_refresh_token": user_account.refresh_token is not None,
    }


def main():
    user_account = UserAccount.objects.select_related("user", "account").get(
        id=USER_ACCOUNT_ID
    )
    token = decrypt_value(user_account.refresh_token)

    print("Initial:")
    print(json.dumps(serialize_user_account(user_account), indent=2))

    for attempt in range(1, ATTEMPTS + 1):
        print(f"Attempt {attempt}/{ATTEMPTS}:")

        response = requests.get(
            f"https://graph.facebook.com/{GRAPH_VERSION}/me/adaccounts",
            params={
                "access_token": token,
                "fields": "id,name,account_id,account_status",
                "limit": 500,
            },
            timeout=30,
        )

        payload = response.json()
        target = None
        if response.ok:
            target = next(
                (
                    row
                    for row in payload.get("data", [])
                    if row.get("account_id") == user_account.account.ad_account_id
                    or row.get("id") == f"act_{user_account.account.ad_account_id}"
                ),
                None,
            )

        print(
            json.dumps(
                {
                    "http_status": response.status_code,
                    "ok": response.ok,
                    "target_account_visible": target is not None,
                    "target_account": target,
                    "error": payload.get("error"),
                },
                indent=2,
            )
        )


main()
