import json
from datetime import datetime, timezone

import requests
from django.conf import settings

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


ACCOUNT_UUID = "39fc431c-493d-4fa6-80db-a993ba6c63d0"
GRAPH_VERSION = getattr(settings, "GRAPH_FB_API_VERSION", "v22.0")


def ts_to_iso(value):
    if not value:
        return None
    return datetime.fromtimestamp(int(value), tz=timezone.utc).isoformat()


def main():
    account = Account.objects.get(id=ACCOUNT_UUID)
    owner_ua = (
        UserAccount.objects.select_related("user", "account")
        .filter(
            account=account,
            role="owner",
            refresh_token__isnull=False,
        )
        .order_by("creation_time_stamp")
        .first()
    )

    if owner_ua is None:
        print("No owner UserAccount with a stored token found.")
        return

    token = decrypt_value(owner_ua.refresh_token)
    app_access_token = f"{settings.FACEBOOK_APP_ID}|{settings.FACEBOOK_APP_SECRET}"

    debug_url = f"https://graph.facebook.com/{GRAPH_VERSION}/debug_token"
    debug_resp = requests.get(
        debug_url,
        params={
            "input_token": token,
            "access_token": app_access_token,
        },
        timeout=30,
    )

    print(
        json.dumps(
            {
                "account": {
                    "id": str(account.id),
                    "ad_account_id": account.ad_account_id,
                    "name": account.ad_account_name,
                    "platform": account.platform,
                },
                "owner_user_account": {
                    "id": str(owner_ua.id),
                    "user_email": owner_ua.user.user_email,
                    "role": owner_ua.role,
                    "current_status": owner_ua.status,
                    "last_token_check_time": owner_ua.last_token_check_time.isoformat()
                    if owner_ua.last_token_check_time
                    else None,
                },
                "debug_token_http_status": debug_resp.status_code,
            },
            indent=2,
            default=str,
        )
    )

    if not debug_resp.ok:
        print("debug_token request failed:")
        print(debug_resp.text)
        return

    debug_data = debug_resp.json().get("data", {})
    print(
        json.dumps(
            {
                "is_valid": debug_data.get("is_valid"),
                "app_id": debug_data.get("app_id"),
                "type": debug_data.get("type"),
                "user_id": debug_data.get("user_id"),
                "expires_at": ts_to_iso(debug_data.get("expires_at")),
                "data_access_expires_at": ts_to_iso(
                    debug_data.get("data_access_expires_at")
                ),
                "scopes": debug_data.get("scopes"),
                "granular_scopes": debug_data.get("granular_scopes"),
                "error": debug_data.get("error"),
            },
            indent=2,
        )
    )

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

    print(
        json.dumps(
            {
                "adaccounts_http_status": adaccounts_resp.status_code,
                "target_ad_account_id": account.ad_account_id,
            },
            indent=2,
        )
    )

    if not adaccounts_resp.ok:
        print("me/adaccounts request failed:")
        print(adaccounts_resp.text)
        return

    rows = adaccounts_resp.json().get("data", [])
    target = next(
        (
            row
            for row in rows
            if row.get("account_id") == account.ad_account_id
            or row.get("id") == f"act_{account.ad_account_id}"
        ),
        None,
    )
    print(json.dumps({"target_account_visible_to_token": target}, indent=2))


main()
