import sys, io, requests
from app.config import settings

if sys.platform == "win32":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

token = settings.META_ACCESS_TOKEN
ig_id = settings.INSTAGRAM_ACCOUNT_ID

# 1. Get recent media
url_media = f"https://graph.facebook.com/v20.0/{ig_id}/media?fields=id,caption,comments_count&limit=5&access_token={token}"
media_list = requests.get(url_media).json().get("data", [])

print(f"Found {len(media_list)} media:")
for m in media_list:
    mid = m["id"]
    cc = m.get("comments_count", 0)
    caption = (m.get("caption") or "")[:40].replace("\n", " ")
    print(f"Post {mid} (Comments: {cc}): {caption}")
    if cc > 0:
        url_comm = f"https://graph.facebook.com/v20.0/{mid}/comments?fields=id,text,timestamp,username,like_count&access_token={token}"
        comments = requests.get(url_comm).json()
        print("  Comments:", comments)
