import requests
import json
import time
import os
from datetime import datetime, timezone

API_KEY = "get-x-api-6157f8edb420c3d5e50e062287389aa55635cd7c9630c81f"
DATE_STR = "2026-06-20"
RESULTS_FILE = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}_CHUNK1.json"

HANDLES = [
    "runwayml", "CuriousRefuge", "nofilmschool", "venturetwins", "Kling_ai",
    "paultrillo", "c_valenzuelab", "CorridorDigital", "karenxcheng", "higgsfield",
    "pika_labs", "EHuanglu", "azed_ai", "JeffSynthesized", "ai_filmmaker",
    "visiblemaker", "Magiermogul", "WuxiaRocks", "JiamingSuen", "moonvalley",
    "higgsfield_ai", "Chandan_Perla"
]

all_results = {"accounts": [], "errors": [], "scan_date": "2026-06-20 06:00 UTC"}
done_handles = set()
if os.path.exists(RESULTS_FILE):
    with open(RESULTS_FILE) as f:
        all_results = json.load(f)
    done_handles = set(a["handle"] for a in all_results["accounts"])
    print(f"Resuming: {len(done_handles)} already scanned")

def parse_date(created_at):
    if not created_at:
        return None
    try:
        dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
        return dt
    except:
        return None

def fetch_tweets(handle):
    url = f"https://api.getxapi.com/twitter/user/tweets?userName={handle}&count=5"
    headers = {"Authorization": f"Bearer {API_KEY}"}
    try:
        resp = requests.get(url, headers=headers, timeout=30)
        resp.raise_for_status()
        data = resp.json()
        tweets = data if isinstance(data, list) else data.get("tweets", data)
        if isinstance(tweets, dict):
            tweets = [tweets]
        return tweets if isinstance(tweets, list) else []
    except Exception as e:
        return {"error": str(e)}

cutoff = datetime.now(timezone.utc).timestamp() - (3 * 86400)

for i, handle in enumerate(HANDLES):
    if handle in done_handles:
        print(f"  SKIP {handle} (already scanned)")
        continue
    
    print(f"  [{i+1}/{len(HANDLES)}] Fetching @{handle}...")
    result = fetch_tweets(handle)
    
    if isinstance(result, dict) and "error" in result:
        print(f"    ERROR: {result['error']}")
        all_results["errors"].append({"handle": handle, "error": result["error"]})
    else:
        account_data = {"handle": handle, "tweets": [], "recent_count": 0, "qualifying_count": 0}
        
        for tweet in result:
            if not isinstance(tweet, dict):
                continue
            
            created_at = tweet.get("createdAt", "")
            dt = parse_date(created_at)
            
            like_count = tweet.get("likeCount") or 0
            retweet_count = tweet.get("retweetCount") or 0
            reply_count = tweet.get("replyCount") or 0
            view_count = tweet.get("viewCount") or 0
            
            is_recent = False
            if dt:
                is_recent = dt.timestamp() >= cutoff
            
            if is_recent:
                account_data["recent_count"] += 1
                
                qualifies = (like_count >= 50 or retweet_count >= 10 or view_count >= 1000)
                
                if qualifies:
                    author = tweet.get("author", {})
                    if isinstance(author, dict):
                        author_user = author.get("userName", handle)
                        author_followers = author.get("followers", 0)
                    else:
                        author_user = handle
                        author_followers = 0
                    
                    tweet_id = tweet.get("id", "")
                    tweet_text = tweet.get("text", "")
                    url = f"https://x.com/{author_user}/status/{tweet_id}" if tweet_id else ""
                    
                    score = like_count + (retweet_count * 2) + reply_count + (view_count // 100)
                    
                    tweet_data = {
                        "id": tweet_id,
                        "text": tweet_text[:200],
                        "url": url,
                        "date": dt.strftime("%Y-%m-%d") if dt else "",
                        "createdAt": created_at,
                        "likeCount": like_count,
                        "retweetCount": retweet_count,
                        "replyCount": reply_count,
                        "viewCount": view_count,
                        "score": score,
                        "author_userName": author_user,
                        "author_followers": author_followers,
                        "is_retweet": tweet_text.startswith("RT @") if tweet_text else False
                    }
                    account_data["tweets"].append(tweet_data)
                    account_data["qualifying_count"] += 1
        
        all_results["accounts"].append(account_data)
        print(f"    {account_data['recent_count']} recent, {account_data['qualifying_count']} qualifying")
    
    with open(RESULTS_FILE + ".tmp", "w") as f:
        json.dump(all_results, f, indent=2)
    
    time.sleep(1)

if os.path.exists(RESULTS_FILE + ".tmp"):
    os.rename(RESULTS_FILE + ".tmp", RESULTS_FILE)
print(f"\nDone! {len(all_results['accounts'])} accounts scanned, {len(all_results['errors'])} errors")
