"""
One-off helper: mint a long-lived PAGE access token from the USER token.

Reads USER_ACCESS_TOKEN, PAGE_ID, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET from .env:
  1. Exchange the user token for a long-lived user token.
  2. Call /me/accounts to get the Page token for PAGE_ID (long-lived, ~no expiry).
  3. Verify it by reading the page feed (the exact call the pipeline makes).
Prints the Page token to paste into PAGE_ACCESS_TOKEN.

Run:  python get_page_token.py
"""

import os
import requests
from dotenv import load_dotenv

load_dotenv()

GRAPH = "https://graph.facebook.com/v19.0"
USER = (os.getenv("USER_ACCESS_TOKEN") or "").strip()
PAGE_ID = (os.getenv("PAGE_ID") or "").strip()
APP_ID = (os.getenv("FACEBOOK_APP_ID") or "").strip()
APP_SECRET = (os.getenv("FACEBOOK_APP_SECRET") or "").strip()


def get(path, params):
    r = requests.get(f"{GRAPH}/{path}", params=params, timeout=30)
    try:
        return r.json()
    except Exception:
        return {}


def main():
    if not USER:
        print("USER_ACCESS_TOKEN is empty in .env — paste your user token there first.")
        return
    if not (APP_ID and APP_SECRET and PAGE_ID):
        print("FACEBOOK_APP_ID / FACEBOOK_APP_SECRET / PAGE_ID missing in .env.")
        return

    # 1) long-lived user token
    print("[1] Exchanging user token for a long-lived user token...")
    data = get("oauth/access_token", {
        "grant_type": "fb_exchange_token",
        "client_id": APP_ID,
        "client_secret": APP_SECRET,
        "fb_exchange_token": USER,
    })
    if "error" in data:
        print("    FAILED:", data["error"].get("message"))
        print("    -> Your user token is likely expired. Generate a fresh one in")
        print("       Graph API Explorer (with pages_show_list, pages_read_engagement,")
        print("       pages_read_user_content) and put it in USER_ACCESS_TOKEN.")
        return
    ll_user = data.get("access_token", USER)
    print("    OK.")

    # 2) page tokens
    print("[2] Fetching your pages (/me/accounts)...")
    data = get("me/accounts", {"access_token": ll_user, "limit": 100})
    if "error" in data:
        print("    FAILED:", data["error"].get("message"))
        return
    pages = data.get("data", [])
    if not pages:
        print("    No pages returned — this user isn't an admin of any page, or the")
        print("    token is missing pages_show_list / pages_read_engagement.")
        return

    print(f"    Found {len(pages)} page(s):")
    page_token = None
    for p in pages:
        mark = ""
        if str(p.get("id")) == PAGE_ID:
            mark = "  <-- target"
            page_token = p.get("access_token")
        print(f"      {p.get('id')}  {p.get('name')}{mark}")

    if not page_token:
        print(f"\n    PAGE_ID {PAGE_ID} is not in that list.")
        print("    Confirm you're an admin of that page and PAGE_ID is correct.")
        return

    # 3) verify against the feed endpoint the pipeline uses
    print("[3] Verifying the page token against the page feed...")
    data = get(f"{PAGE_ID}/feed", {"access_token": page_token, "limit": 1})
    if "error" in data:
        print("    FAILED:", data["error"].get("message"))
        return
    print("    OK — the feed returned data. This is a valid Page token.")

    print("\n" + "=" * 64)
    print("PAGE ACCESS TOKEN  (paste into PAGE_ACCESS_TOKEN):")
    print(page_token)
    print("=" * 64)
    print("Put it where the code reads it: the admin API Keys page if a DB value")
    print("is set, otherwise .env PAGE_ACCESS_TOKEN. Then re-run probe_feed_order.py.")


if __name__ == "__main__":
    main()
